﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.CUiAPPMainWindow
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.AutomaticPathPlanner;
using EngineeringInternalExtension;
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui.WPF;


namespace DnProcessSimulateCommands;

public class CUiAPPMainWindow : 
  TxWindow,
  INotifyPropertyChanged,
  IComponentConnector,
  IStyleConnector
{
  private CUiAPPAutomaticPathPlannerCmd m_command;
  private CApAPPPlanManager m_planManager;
  private CApAPPParameterController m_parameterController;
  private TxObjectList m_originalSelectedOperations;
  private CApAPPTaskManager m_taskManager;
  private KiAppPathPlanningParamsEx m_pathPlanningParams;
  private KiAppPathPlanningParamsEx m_defaultPathPlanningParams;
  private List<List<CApAPPWaypoint>> m_originalWaypointList;
  private readonly List<ITxSectionVolume> m_activeSections;
  private CUiAPPMainWindow.PathPlanningUIStatus m_currentPlanningStep;
  private bool m_isUpdateDisplayEnabled;
  private bool m_preProcessingActivated = true;
  private bool m_wasUpdateDisplayEnabledBeforeMagnetPoint;
  private bool m_isRCSEnergyCapable;
  private bool m_wasIgnoreLogicOLPCommands;
  private bool m_wasSimulationFixerDeactivated = true;
  private List<ITxOperation> m_backupOperationlist = new List<ITxOperation>();
  private CUiAPPLocationsDataGrid m_locationsGrid;
  private ITxOperation m_startOperation;
  private ITxOperation m_endOperation;
  private bool m_firstTime = true;
  private CUiAPPMainWindow.PlanType m_currentPlanType;
  private List<CApAPPClearanceOptimizationCollisionSetData> m_clearanceOptimDataList;
  private bool m_wasCollisionCheckEnabledBeforePlanning;
  private bool m_isWindowLoading;
  private double m_oldRealHeight;
  private bool m_isGridResized;
  private bool m_isFlexGridGroupCollapsedChanged;
  private bool m_isModeWithoutRefreshEnabled;
  private bool m_wasKineoForAppAvailableOnStartUp;
  private string m_statusMessage = "";
  private double m_theoriticalWindowHeight = -1.0;
  private const uint SC_CLOSE = 61536;
  private const uint MF_GRAYED = 1;
  private const uint MF_ENABLED = 0;
  private CApAPPAnalytics m_analytics;
  internal CUiAPPMainWindow dMainDialog;
  internal System.Windows.Controls.DataGrid fgLocationGrid;
  internal DataGridTemplateColumn m_fgLocationGrid_pathAndLocationColumn;
  internal DataGridTemplateColumn m_fgLocationGrid_fixedColumn;
  internal DataGridTemplateColumn m_fgLocationGrid_motionColumn;
  internal DataGridTemplateColumn m_fgLocationGrid_zoneColumn;
  internal DataGridTemplateColumn m_fgLocationGrid_clashColumn;
  internal DataGridTemplateColumn m_fgLocationGrid_statusColumn;
  internal System.Windows.Controls.ContextMenu fgContextMenu;
  internal Expander exPlan;
  internal System.Windows.Controls.ProgressBar pgbPlanningProgressBar;
  internal TextBlock tbPlanTime;
  internal System.Windows.Controls.Button btnPlan;
  internal StackPanel spPlan;
  internal System.Windows.Controls.ComboBox cbQuality;
  internal System.Windows.Controls.CheckBox cbActivatedExtraction;
  internal System.Windows.Controls.CheckBox cbConsiderActiveSection;
  internal TextBlock lblActiveSectionName;
  internal System.Windows.Controls.CheckBox cbIncludeDevice;
  internal System.Windows.Controls.CheckBox cbCheckCableTwisting;
  internal StackPanel spMaxJ4J6;
  internal TextBlock tbMaxJ4J6Title;
  internal System.Windows.Controls.TextBox tbMaxJ4J6Value;
  internal TextBlock tbMaxJ4J6Unit;
  internal Grid gridApproachDepartAndPreProcess;
  internal RowDefinition preProcessingActivation;
  internal RowDefinition ApproachDepartCreationParameters;
  internal StackPanel PreProcessingPanel;
  internal System.Windows.Controls.CheckBox cbActivatePreProcessing;
  internal StackPanel ApproachDepartMakerPanel;
  internal System.Windows.Controls.CheckBox cbApproachDepartCreation;
  internal RowDefinition openingGunRow;
  internal RowDefinition perpendicularAdj;
  internal TextBlock cbOpeningGun;
  internal TxNumericEditBoxControl TxNumericEditBoxOpeningGunValue;
  internal TextBlock tbOpeningLinearUnitLabel;
  internal TextBlock cbPerpendicularAdjustment;
  internal TxNumericEditBoxControl TxNumericEditBoxOptimizationPerpendicularAdujustment;
  internal TextBlock tbPerpendicularLinearUnitLabel;
  internal StackPanel ObjectFlowPathPlanningPanel;
  internal System.Windows.Controls.CheckBox cbUpdateDisplay;
  internal StackPanel magnetPointPanel;
  internal ToggleButton btnMagnetPoint;
  internal System.Windows.Controls.Button btnResetMagnetPoint;
  internal CApAPPLimitsUserControl LimitsUserControl;
  internal Expander exOptimization;
  internal System.Windows.Controls.ProgressBar pgbOptimizationProgressBar;
  internal TextBlock tbOptimizationTime;
  internal System.Windows.Controls.Button btnOptimize;
  internal Grid gridOptimizationType;
  internal RowDefinition JointTravelAndCycleTimeRadioButtonRow;
  internal System.Windows.Controls.ComboBox cbOptimizationType;
  internal TextBlock JointTravelOptimizationTypeTextBox;
  internal TextBlock CycleTimeOptimizationTypeTextBox;
  internal StackPanel JointTravelOptimizationType;
  internal System.Windows.Controls.RadioButton QuickJointTravelRadioButton;
  internal System.Windows.Controls.RadioButton PreciseJointTravelRadioButton;
  internal StackPanel CycleTimeOptimizationType;
  internal System.Windows.Controls.RadioButton ZoneAssigmentCycleTimeRadioButton;
  internal System.Windows.Controls.RadioButton FullCycleTimeRadioButton;
  internal Grid gridOptimization;
  internal Grid gridNewFullCycleTime;
  internal System.Windows.Controls.CheckBox m_ctoEnableTargetCycleTime;
  internal TxNumericEditBoxControl TxNumericEditBoxOptimizationCycleTimeTarget;
  internal TextBlock m_ctoOptimizationTargetCycleTimeUnitLabelNewFull;
  internal System.Windows.Controls.CheckBox m_ctoEnableTimeLimitLabelNewFull;
  internal TxNumericEditBoxControl TxNumericEditBoxOptimizationTimeLimitNewFull;
  internal TextBlock m_ctoOptimizationTimeOutUnitLabelNewFull;
  internal Grid gdClearanceOpt;
  internal TxNumericEditBoxControl tbClearanceOptStepSize;
  internal TextBlock tbClearanceOptUnit;
  internal System.Windows.Controls.DataGrid fgDesiredClearances;
  internal TxNumericEditBoxControl TxNumericEditBoxEnergyMaxCycleTimeIncrease;
  internal TxNumericEditBoxControl TxNumericEditBoxEnergyMaxJointSpeed;
  internal TxNumericEditBoxControl TxNumericEditBoxEnergyMaxLinearSpeed;
  internal System.Windows.Controls.CheckBox m_energyEnableTimeLimitCheckBox;
  internal TxNumericEditBoxControl TxNumericEditBoxEnergyTimeLimit;
  internal TextBlock m_energyOptimizationTimeOutUnitLabel;
  internal Expander exPlanAndOptimization;
  internal TextBlock tbPlanAndOptimizationTime;
  internal System.Windows.Controls.ProgressBar pgbPlanningAndOptimizationProgressBar;
  internal System.Windows.Controls.Button btnPlanAndOptimize;
  internal StackPanel spPlanAndOptimization;
  internal Expander exGeneralOption;
  internal CUiAPPGeneralSettings m_generalSettingsControl;
  internal System.Windows.Controls.Button btnReset;
  internal System.Windows.Controls.Button btnClose;
  internal Image iErrorIcon;
  internal TextBlock lblPathPlanningStatus;
  internal TextBlock tbMessage;
  private bool _contentLoaded;

  [DllImport("user32.dll")]
  private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

  [DllImport("user32.dll")]
  private static extern int EnableMenuItem(IntPtr hMenu, uint wIDEnableItem, uint wEnable);

  public CUiAPPMainWindow(CUiAPPAutomaticPathPlannerCmd command)
  {
    this.m_analytics = new CApAPPAnalytics();
    this.m_command = command;
    this.ShouldBeStarted = true;
    this.m_isWindowLoading = true;
    this.m_isGridResized = false;
    this.m_oldRealHeight = 0.0;
    this.m_activeSections = this.GetActiveSections();
    this.GUIParameters = new CUiAPPMainWindowGUIParameters();
    this.TaskGUIParameters = new CApAPPTaskGUIParameters();
    this.KineoForAppPlanningParameters = new CUiAPPKineoForAppPlanningParameters();
    this.m_wasKineoForAppAvailableOnStartUp = this.IsKineoForAppAvailable;
    this.DisableLogicOLPCommands();
    this.DisableSimulationFixer();
    this.InitSelectionList();
    if (this.m_originalSelectedOperations != null)
    {
      this.m_analytics.LogSelectedOperations(this.m_originalSelectedOperations);
      this.CreateTaskManager();
      if (!this.ShouldBeStarted)
        return;
      this.InitTaskManager();
      this.InitParameters();
      this.InitializeComponent();
      this.InitParameterController();
      if (this.m_taskManager.IsObjectFlowMode)
      {
        this.LimitsUserControl.TaskManager = this.m_taskManager;
        this.LimitsUserControl.PathPlanningParams = this.m_pathPlanningParams;
        this.LimitsUserControl.TaskGUIParameters = this.TaskGUIParameters;
        this.LimitsUserControl.InitLimits();
        this.LimitsUserControl.LimitError.PropertyChanged += new PropertyChangedEventHandler(this.LimitError_PropertyChanged);
      }
      else
        this.LimitsUserControl.Visibility = Visibility.Collapsed;
      this.InitGrid();
      this.CheckRCSEnergyCapability();
      this.InitOptimizationCombo();
      this.DisplayInitErrors();
      this.m_generalSettingsControl.RestoreDefaultValuesTriggered += new EventHandler(this.onRestoreDefaultTriggered);
    }
    else
      this.ShouldBeStarted = false;
  }

  private double UpperPerpendicularAdjustment { get; set; }

  private double LowerPerpendicularAdjustment { get; set; }

  private double LowerOpeningGunValue { get; set; }

  private double UpperOpeningGunValue { get; set; }

  private double PerpendicularAdjustment { get; set; }

  private double OpeningGunValue { get; set; }

  private void LimitError_PropertyChanged(object sender, PropertyChangedEventArgs e)
  {
    this.UpdateLimitErrorDisplay();
  }

  private void UpdateLimitErrorDisplay()
  {
    bool flag = this.LimitsUserControl.LimitError.ErrorType != 0;
    this.ClearLimitsExceedErrorPlanSuccess();
    if (flag)
    {
      this.AllPanningButtonSensitivity(false);
      this.iErrorIcon.Visibility = Visibility.Visible;
      this.UpdateErrorLimitsIcons(this.LimitsUserControl.LimitError.WaypointsWithTranslationError, this.LimitsUserControl.LimitError.WaypointsWithRotationError);
      this.StatusMessage = this.LimitsUserControl.LimitError.ErrorMessageToDisplay;
    }
    else
    {
      this.AllPanningButtonSensitivity(true);
      this.iErrorIcon.Visibility = Visibility.Hidden;
      this.StatusMessage = this.LimitsUserControl.LimitError.ErrorMessageToDisplay;
    }
  }

  public bool IsLimitsModifying { get; set; }

  public bool ShouldBeStarted { get; set; }

  public bool IsUnknowErrorDisplayed { get; set; }

  public KiAppPathPlanningParamsEx PathPlanningParams => this.m_pathPlanningParams;

  public CUiAPPMainWindow.PathPlanningUIStatus PathPlanningStatus
  {
    get => this.m_currentPlanningStep;
    set
    {
      this.m_currentPlanningStep = value;
      this.NotifyPropertyChanged(nameof (PathPlanningStatus));
    }
  }

  public bool IsKineoForAppAvailable
  {
    get => this.IsKineoForAppPathPlanningAvailable || this.IsKineoForAppTrajectoryPlanningAvailable;
  }

  public bool IsKineoForAppPathPlanningAvailable
  {
    get => CApAPPUtilities.IsKineoForAppPathPlanningAvailable();
  }

  public bool IsKineoForAppTrajectoryPlanningAvailable
  {
    get => CApAPPUtilities.IsKineoForAppTrajectoryPlanningAvailable();
  }

  public bool IsKineoForAppPlanningActive
  {
    get => this.KineoForAppPlanningParameters.IsActive;
    set
    {
      if (value == this.IsKineoForAppPlanningActive)
        return;
      this.KineoForAppPlanningParameters.IsActive = value;
      this.NotifyPropertyChanged(nameof (IsKineoForAppPlanningActive));
    }
  }

  public CUiAPPKineoForAppPlanningParameters.KineoForAppPlanningType KineoForAppPlanningType
  {
    get => this.KineoForAppPlanningParameters.PlanningType;
    set
    {
      if (value == this.KineoForAppPlanningType)
        return;
      this.KineoForAppPlanningParameters.PlanningType = value;
      this.NotifyPropertyChanged(nameof (KineoForAppPlanningType));
    }
  }

  private bool ShouldUseKineoForAppPlanning
  {
    get
    {
      return this.m_currentPlanType == CUiAPPMainWindow.PlanType.PLAN && this.IsKineoForAppAvailable && this.IsKineoForAppPlanningActive;
    }
  }

  public bool IsPreProcessingActivated
  {
    get
    {
      bool processingActivated = false;
      if (this.m_taskManager != null)
        processingActivated = this.PathPlanningParams.IsPreProcessingActivated && this.m_taskManager.ContainsWeldOperation;
      return processingActivated;
    }
    set => this.PathPlanningParams.IsPreProcessingActivated = value;
  }

  public bool IsApproachDepartCreationActivated
  {
    get
    {
      bool creationActivated = false;
      if (this.m_taskManager != null)
        creationActivated = this.PathPlanningParams.IsApproachDepartCreationActivated && this.m_taskManager.ContainsWeldOperation;
      return creationActivated;
    }
    set => this.PathPlanningParams.IsApproachDepartCreationActivated = value;
  }

  public bool IsUpdateDisplayEnabled
  {
    get => this.m_isUpdateDisplayEnabled;
    set
    {
      this.m_isUpdateDisplayEnabled = value;
      if (this.m_currentPlanType != CUiAPPMainWindow.PlanType.NONE)
      {
        if (this.m_isUpdateDisplayEnabled)
          this.m_planManager.EnableShowLastAddedPosition();
        else
          this.m_planManager.DisableShowLastAddedPosition();
      }
      this.NotifyPropertyChanged(nameof (IsUpdateDisplayEnabled));
    }
  }

  public string StatusMessage
  {
    get => this.m_statusMessage;
    set
    {
      this.m_statusMessage = value;
      this.NotifyPropertyChanged(nameof (StatusMessage));
    }
  }

  private void ClearLimitsExceedErrorPlanSuccess()
  {
    foreach (CApAPPTask task in this.m_taskManager.Tasks)
    {
      foreach (CApAPPWaypoint waypoint in task.Waypoints())
      {
        if (waypoint.WaypointPlanSuccess == CApAPPWaypointPlanSuccess.RotationLimitsExceededError || waypoint.WaypointPlanSuccess == CApAPPWaypointPlanSuccess.TranslationLimitsExceededError || waypoint.WaypointPlanSuccess == CApAPPWaypointPlanSuccess.TranslationAndRotationLimitsExceededError)
          waypoint.WaypointPlanSuccess = CApAPPWaypointPlanSuccess.Regular;
      }
    }
  }

  private void UpdateErrorLimitsIcons(
    List<CApAPPWaypoint> translationWps,
    List<CApAPPWaypoint> rotationWps)
  {
    foreach (CApAPPWaypoint translationWp in translationWps)
      translationWp.WaypointPlanSuccess = CApAPPWaypointPlanSuccess.TranslationLimitsExceededError;
    foreach (CApAPPWaypoint rotationWp in rotationWps)
      rotationWp.WaypointPlanSuccess = CApAPPWaypointPlanSuccess.RotationLimitsExceededError;
    foreach (CApAPPWaypoint translationWp in translationWps)
    {
      foreach (CApAPPWaypoint rotationWp in rotationWps)
      {
        if (((ITxObject) translationWp.Task.Operation).Id == ((ITxObject) rotationWp.Task.Operation).Id && translationWp.WaypointRank == rotationWp.WaypointRank)
          translationWp.WaypointPlanSuccess = CApAPPWaypointPlanSuccess.TranslationAndRotationLimitsExceededError;
      }
    }
    this.m_locationsGrid.Refresh(CApAPPWaypointProperty.Status);
  }

  public bool IsRCSEnergyIncapable => !this.m_isRCSEnergyCapable;

  public CUiAPPMainWindowGUIParameters GUIParameters { get; private set; }

  public CApAPPTaskGUIParameters TaskGUIParameters { get; private set; }

  public CUiAPPKineoForAppPlanningParameters KineoForAppPlanningParameters { get; }

  private void DisableLogicOLPCommands()
  {
    this.m_wasIgnoreLogicOLPCommands = TxApplication.Options.Simulation.IgnoreRobotLogic;
    TxApplication.Options.Simulation.IgnoreRobotLogic = true;
  }

  private void RestoreLogicOLPCommands()
  {
    if (TxApplication.Options.Simulation.IgnoreRobotLogic == this.m_wasIgnoreLogicOLPCommands)
      return;
    TxApplication.Options.Simulation.IgnoreRobotLogic = this.m_wasIgnoreLogicOLPCommands;
  }

  private void DisableSimulationFixer()
  {
    this.m_wasSimulationFixerDeactivated = TxApplication.Options.Simulation.DisableSimulationFixer;
    TxApplication.Options.Simulation.DisableSimulationFixer = true;
  }

  private void RestoreSimulationFixer()
  {
    if (TxApplication.Options.Simulation.DisableSimulationFixer == this.m_wasSimulationFixerDeactivated)
      return;
    TxApplication.Options.Simulation.DisableSimulationFixer = this.m_wasSimulationFixerDeactivated;
  }

  private void TxWindow_Loaded(object sender, RoutedEventArgs e)
  {
    this.StartUndoTransaction();
    this.m_locationsGrid.UpdateView();
    this.InitDialog();
    this.TxNumericEditBoxEnergyMaxLinearSpeed.DecimalPlaces = 2;
    if (!this.m_taskManager.IsObjectFlowMode)
      this.iErrorIcon.Visibility = Visibility.Hidden;
    this.RegisterSimulationEvents();
  }

  public void App_Activated(object sender, EventArgs e)
  {
    if (!this.m_firstTime)
      return;
    this.m_generalSettingsControl.SetParentIsActivated();
    this.m_isWindowLoading = false;
    this.m_firstTime = false;
    ((FrameworkElement) this).MinHeight = ((FrameworkElement) this).ActualHeight;
    ((FrameworkElement) this).MaxHeight = ((FrameworkElement) this).ActualHeight;
    if (this.LimitsUserControl.IsInitialized)
    {
      this.LimitsUserControl.OnParentWindowActivated();
      this.LimitsUserControl.UpdateTranslationLimitWallsDisplay();
      this.LimitsUserControl.UpdateLimitError();
    }
    else
      this.StatusMessage = "";
  }

  private void TxWindow_Closed(object sender, CancelEventArgs e)
  {
    if (this.m_taskManager.IsObjectFlowMode)
      this.LimitsUserControl.OnClose();
    this.m_locationsGrid.UnregisterSelectionEvents();
    this.EndUndoTransaction();
    this.UnregisterSimulationEvents();
    this.m_analytics.LogElapsedTime();
  }

  private void InitGrid()
  {
    this.m_locationsGrid = new CUiAPPLocationsDataGrid(this.fgLocationGrid, this.m_taskManager);
    if (this.m_startOperation == null || this.m_endOperation == null)
      return;
    int o_indexTask = 0;
    int o_indexWaypoint1 = 0;
    int o_indexWaypoint2 = 0;
    this.m_taskManager.retrieveWaypointIndexFromOperation(this.m_startOperation, ref o_indexTask, ref o_indexWaypoint1);
    this.m_taskManager.retrieveWaypointIndexFromOperation(this.m_endOperation, ref o_indexTask, ref o_indexWaypoint2);
    if (o_indexWaypoint1 < o_indexWaypoint2)
      this.m_taskManager.Tasks[o_indexTask].SetActiveRange(o_indexWaypoint1, o_indexWaypoint2);
    else
      this.m_taskManager.Tasks[o_indexTask].SetActiveRange(o_indexWaypoint2, o_indexWaypoint1);
  }

  private void InitOptimizationCombo()
  {
    List<string> stringList = new List<string>();
    ObservableCollection<CApAPPOptimizationComboBoxItem> observableCollection = new ObservableCollection<CApAPPOptimizationComboBoxItem>();
    if (this.m_taskManager.IsObjectFlowMode)
    {
      observableCollection.Add(new CApAPPOptimizationComboBoxItem(CApAPPMainWindowStringTable.AppOptimizationLength, CApAPPPlanningType.JOINTTRAVEL_OPT, (KiAppOptimizationOption) 0));
      observableCollection.Add(new CApAPPOptimizationComboBoxItem(CApAPPMainWindowStringTable.AppOptimizationDesiredClearance, CApAPPPlanningType.CLEARANCE_OPT, (KiAppOptimizationOption) 1));
    }
    else
    {
      observableCollection.Add(new CApAPPOptimizationComboBoxItem(CApAPPMainWindowStringTable.AppOptimizationJointTravel, CApAPPPlanningType.JOINTTRAVEL_OPT, (KiAppOptimizationOption) 0));
      observableCollection.Add(new CApAPPOptimizationComboBoxItem(CApAPPMainWindowStringTable.AppOptimizationDesiredClearance, CApAPPPlanningType.CLEARANCE_OPT, (KiAppOptimizationOption) 1));
      observableCollection.Add(new CApAPPOptimizationComboBoxItem(CApAPPMainWindowStringTable.AppOptimizationCycleTime, CApAPPPlanningType.CYCLETIME_OPT, (KiAppOptimizationOption) 2));
      if (this.m_isRCSEnergyCapable)
        observableCollection.Add(new CApAPPOptimizationComboBoxItem(CApAPPMainWindowStringTable.AppOptimizationEnergy, CApAPPPlanningType.ENERGY_OPT, (KiAppOptimizationOption) 3));
    }
    this.cbOptimizationType.ItemsSource = (IEnumerable) observableCollection;
  }

  private void dMainDialog_SizeChanged(object sender, SizeChangedEventArgs e)
  {
    if (!e.WidthChanged)
      return;
    ((Window) this).SizeToContent = SizeToContent.Height;
  }

  private void Expander_SizeChanged(object sender, SizeChangedEventArgs e)
  {
    Size size = e.NewSize;
    double height1 = size.Height;
    size = e.PreviousSize;
    double height2 = size.Height;
    this.UpdateWindowHeight(height1 - height2);
  }

  private void UpdateWindowHeight(double heightDifference)
  {
    if (this.m_isWindowLoading || heightDifference == 0.0)
      return;
    // ISSUE: explicit non-virtual call
    double num = this.m_oldRealHeight != 0.0 ? this.m_oldRealHeight + heightDifference : (((FrameworkElement) this).MinHeight != ((FrameworkElement) this).MaxHeight || this.m_theoriticalWindowHeight <= 0.0 ? __nonvirtual (((FrameworkElement) this).Height) + heightDifference : this.m_theoriticalWindowHeight + heightDifference);
    if (num > SystemParameters.WorkArea.Height)
    {
      this.m_oldRealHeight = num;
      ((FrameworkElement) this).MinHeight = SystemParameters.WorkArea.Height;
      ((FrameworkElement) this).MaxHeight = SystemParameters.WorkArea.Height;
    }
    else
    {
      this.m_theoriticalWindowHeight = num;
      ((FrameworkElement) this).MinHeight = Math.Ceiling(this.m_theoriticalWindowHeight);
      ((FrameworkElement) this).MaxHeight = Math.Ceiling(this.m_theoriticalWindowHeight);
      this.m_oldRealHeight = 0.0;
    }
  }

  private void CheckRCSEnergyCapability()
  {
    this.m_isRCSEnergyCapable = false;
    if (this.m_taskManager.Tasks.Count <= 0 || !(this.m_taskManager.Tasks[0] is CApAPPRoboticTask task))
      return;
    TxRobot robot = task.Robot as TxRobot;
    if (!CApAPPUtilities.CanUseRCSForRobot((ITxRobot) robot))
      return;
    TxRRSServicesProvider servicesProvider;
    try
    {
      servicesProvider = new TxRRSServicesProvider(robot);
    }
    catch (TxRRSCanNotInitializeRcsException ex)
    {
      servicesProvider = (TxRRSServicesProvider) null;
    }
    if (servicesProvider == null)
      return;
    this.m_isRCSEnergyCapable = servicesProvider.DoesRCSSupportEnergy(robot);
  }

  private void InitSelectionList()
  {
    TxObjectList filteredItems = TxApplication.ActiveSelection.GetFilteredItems((ITxTypeFilter) new TxTypeFilter(typeof (ITxOperation)));
    TxObjectList txObjectList = new TxObjectList();
    if (((Collection<ITxObject>) filteredItems).Count <= 0)
      return;
    if (((Collection<ITxObject>) filteredItems).Count >= 2 && (((Collection<ITxObject>) filteredItems)[0] is ITxLocationOperation || ((Collection<ITxObject>) filteredItems)[0] is TxRoboticSeamOperation) && (((Collection<ITxObject>) filteredItems)[((Collection<ITxObject>) filteredItems).Count - 1] is ITxLocationOperation || ((Collection<ITxObject>) filteredItems)[((Collection<ITxObject>) filteredItems).Count - 1] is TxRoboticSeamOperation))
    {
      ITxOperation collection = (ITxOperation) ((Collection<ITxObject>) filteredItems)[0].Collection;
      this.m_originalSelectedOperations = new TxObjectList();
      ((Collection<ITxObject>) this.m_originalSelectedOperations).Add((ITxObject) collection);
      this.m_startOperation = ((Collection<ITxObject>) filteredItems)[0] as ITxOperation;
      this.m_endOperation = ((Collection<ITxObject>) filteredItems)[((Collection<ITxObject>) filteredItems).Count - 1] as ITxOperation;
    }
    else
      this.m_originalSelectedOperations = filteredItems;
  }

  private void CreateTaskManager()
  {
    this.m_taskManager = new CApAPPTaskManager(this.m_originalSelectedOperations);
    this.DisplayBlockingInitErrors();
  }

  private void InitTaskManager()
  {
    this.m_originalWaypointList = new List<List<CApAPPWaypoint>>();
    for (int index = 0; index < this.m_taskManager.CountTasks(); ++index)
      this.m_originalWaypointList.Add(this.m_taskManager.Tasks[index].CreateWaypointListCopy());
    if (this.m_taskManager.IsObjectFlowMode)
      this.RegisterObjectFlowAbsoluteLocationChangedEvent();
    string zoneLabel = this.m_originalWaypointList[0][1].ZoneLabel;
  }

  private void InitParameterController()
  {
    this.m_parameterController = new CApAPPParameterController(this.m_command, this.m_taskManager, this.m_pathPlanningParams, this.TaskGUIParameters, this.KineoForAppPlanningParameters, this.GUIParameters);
    this.m_parameterController.Load();
    this.m_fgLocationGrid_clashColumn.Width = new DataGridLength(this.GUIParameters.LocationGrid_ClashColumnWidth);
    this.m_fgLocationGrid_fixedColumn.Width = new DataGridLength(this.GUIParameters.LocationGrid_FixedColumnWidth);
    this.m_fgLocationGrid_motionColumn.Width = new DataGridLength(this.GUIParameters.LocationGrid_MotionColumnWidth);
    this.m_fgLocationGrid_pathAndLocationColumn.Width = new DataGridLength(this.GUIParameters.LocationGrid_PathAndLocationsColumnWidth);
    this.m_fgLocationGrid_zoneColumn.Width = new DataGridLength(this.GUIParameters.LocationGrid_ZoneColumnWidth);
  }

  private void InitParameters()
  {
    this.m_defaultPathPlanningParams = new KiAppPathPlanningParamsEx();
    this.m_defaultPathPlanningParams.Quality = (KiAppPathPlanningQuality) 1;
    this.m_defaultPathPlanningParams.JointTravelOptimization = (KiAppJointTravelOptimization) 0;
    this.m_defaultPathPlanningParams.OptimizationOption = (KiAppOptimizationOption) 0;
    this.m_defaultPathPlanningParams.ExtractionIsActivated = true;
    this.m_defaultPathPlanningParams.SectionIsActivated = false;
    this.m_defaultPathPlanningParams.TimeOutIsActivated = false;
    this.m_defaultPathPlanningParams.IncludeDeviceInActiveSection = false;
    this.m_defaultPathPlanningParams.BackUpOperationIsActivated = false;
    this.m_defaultPathPlanningParams.CheckCableTwistingIsActivated = false;
    this.m_defaultPathPlanningParams.DesiredClearanceStepSize = 2.0;
    this.m_defaultPathPlanningParams.TimeOut = 1800.0;
    this.m_defaultPathPlanningParams.MaxAbsJ4J6 = 2.0 * Math.PI;
    this.m_defaultPathPlanningParams.CTOMode = (KiAppCTOMode) 0;
    this.m_defaultPathPlanningParams.EnergyMaxCycleTimeIncrease = 5.0;
    this.m_defaultPathPlanningParams.RobotTotalMass = 1000.0;
    this.m_defaultPathPlanningParams.Payload = 0.0;
    this.m_defaultPathPlanningParams.SimulationTimeInterval = 0.01;
    this.m_defaultPathPlanningParams.RobotMaxJointSpeed = 100.0;
    this.m_defaultPathPlanningParams.RobotMaxLinearSpeed = 2000.0;
    this.m_defaultPathPlanningParams.ShouldDeeplyOptimize = false;
    this.m_defaultPathPlanningParams.IsOptimizationTimeLimitEnabled = false;
    this.m_defaultPathPlanningParams.OptimizationTimeLimit = 20.0;
    this.m_defaultPathPlanningParams.IsOptimizationCycleTimeTargetEnabled = false;
    this.m_defaultPathPlanningParams.OptimizationCycleTimeTarget = 20.0;
    this.m_pathPlanningParams = new KiAppPathPlanningParamsEx(this.m_defaultPathPlanningParams);
  }

  private void InitDialog()
  {
    this.m_generalSettingsControl.Initialize(this.m_pathPlanningParams, this.m_taskManager);
    this.tbClearanceOptUnit.Text = TxApplication.Options.Units.LinearUnitName;
    this.tbMaxJ4J6Unit.Text = TxApplication.Options.Units.AngularUnitName;
    this.tbOpeningLinearUnitLabel.Text = TxApplication.Options.Units.LinearUnitName;
    this.tbPerpendicularLinearUnitLabel.Text = TxApplication.Options.Units.LinearUnitName;
    this.SelectCbOptimizationTypeFromOption(this.m_pathPlanningParams.OptimizationOption);
    KiAppJointTravelOptimization travelOptimization = this.m_pathPlanningParams.JointTravelOptimization;
    if (travelOptimization != null)
    {
      if (travelOptimization == 1)
      {
        this.PreciseJointTravelRadioButton.IsChecked = new bool?(true);
        this.QuickJointTravelRadioButton.IsChecked = new bool?(false);
      }
      else
        this.QuickJointTravelRadioButton.IsChecked = new bool?(true);
    }
    else
      this.QuickJointTravelRadioButton.IsChecked = new bool?(true);
    switch ((int) this.m_pathPlanningParams.CTOMode)
    {
      case 0:
        this.ZoneAssigmentCycleTimeRadioButton.IsChecked = new bool?(true);
        break;
      case 1:
        this.FullCycleTimeRadioButton.IsChecked = new bool?(true);
        break;
      case 2:
        this.FullCycleTimeRadioButton.IsChecked = new bool?(true);
        break;
      default:
        this.ZoneAssigmentCycleTimeRadioButton.IsChecked = new bool?(true);
        break;
    }
    this.m_ctoOptimizationTimeOutUnitLabelNewFull.Text = TxApplication.Options.Units.TimeUnitName;
    this.m_ctoOptimizationTargetCycleTimeUnitLabelNewFull.Text = TxApplication.Options.Units.TimeUnitName;
    this.m_energyOptimizationTimeOutUnitLabel.Text = TxApplication.Options.Units.TimeUnitName;
    this.cbActivatedExtraction.IsChecked = new bool?(this.m_pathPlanningParams.ExtractionIsActivated);
    this.m_ctoEnableTargetCycleTime.IsChecked = new bool?(this.m_pathPlanningParams.IsOptimizationCycleTimeTargetEnabled);
    ((UIElement) this.TxNumericEditBoxOptimizationCycleTimeTarget).IsEnabled = this.m_ctoEnableTargetCycleTime.IsChecked.GetValueOrDefault();
    this.m_ctoEnableTimeLimitLabelNewFull.IsChecked = new bool?(this.m_pathPlanningParams.IsOptimizationTimeLimitEnabled);
    TxNumericEditBoxControl timeLimitNewFull = this.TxNumericEditBoxOptimizationTimeLimitNewFull;
    bool? isChecked = this.m_ctoEnableTimeLimitLabelNewFull.IsChecked;
    int num1 = isChecked.GetValueOrDefault() ? 1 : 0;
    ((UIElement) timeLimitNewFull).IsEnabled = num1 != 0;
    double num2 = TxApplication.Options.Units.LinearMultiplier == 0.0 ? 1.0 : TxApplication.Options.Units.LinearMultiplier;
    this.cbQuality.SelectedIndex = (int) this.m_pathPlanningParams.Quality;
    this.OptimizationChanged();
    this.InitClearanceOptimizationData();
    this.cbConsiderActiveSection.IsChecked = new bool?(false);
    this.cbIncludeDevice.IsChecked = new bool?(false);
    this.cbIncludeDevice.IsEnabled = false;
    this.DisplayActiveSection();
    if (this.cbConsiderActiveSection.IsEnabled)
    {
      bool flag1 = true;
      if (this.m_activeSections.Count == 1)
      {
        flag1 = ((ITxObject) this.m_activeSections[0]).Name == this.m_pathPlanningParams.ActiveSectionName;
        this.m_pathPlanningParams.ActiveSectionName = ((ITxObject) this.m_activeSections[0]).Name;
      }
      else
        this.m_pathPlanningParams.ActiveSectionName = "";
      this.cbConsiderActiveSection.IsChecked = new bool?(this.m_pathPlanningParams.SectionIsActivated & flag1);
      KiAppPathPlanningParamsEx pathPlanningParams = this.m_pathPlanningParams;
      isChecked = this.cbConsiderActiveSection.IsChecked;
      int num3 = isChecked.Value ? 1 : 0;
      pathPlanningParams.SectionIsActivated = num3 != 0;
      this.cbIncludeDevice.IsChecked = new bool?(false);
      this.cbIncludeDevice.IsEnabled = false;
      isChecked = this.cbConsiderActiveSection.IsChecked;
      bool flag2 = true;
      if (isChecked.GetValueOrDefault() == flag2 & isChecked.HasValue)
      {
        if (this.cbConsiderActiveSection.IsEnabled)
          this.cbIncludeDevice.IsEnabled = !this.m_taskManager.IsObjectFlowMode;
        this.cbIncludeDevice.IsChecked = new bool?(this.m_pathPlanningParams.IncludeDeviceInActiveSection);
      }
    }
    this.cbCheckCableTwisting.IsChecked = new bool?(this.m_pathPlanningParams.CheckCableTwistingIsActivated);
    StackPanel spMaxJ4J6 = this.spMaxJ4J6;
    isChecked = this.cbCheckCableTwisting.IsChecked;
    int num4 = isChecked.Value ? 1 : 0;
    spMaxJ4J6.IsEnabled = num4 != 0;
    this.tbMaxJ4J6Value.Text = Convert.ToString(Math.Round(this.m_pathPlanningParams.MaxAbsJ4J6 / TxApplication.Options.Units.AngularMultiplier, 2));
    if (this.m_taskManager.IsObjectFlowMode)
    {
      this.HideSpecificRoboticControls();
      this.btnMagnetPoint.IsChecked = new bool?(false);
      this.cbUpdateDisplay.IsChecked = new bool?(false);
      this.LimitsUserControl.UpdateLimitError();
    }
    else
    {
      this.ObjectFlowPathPlanningPanel.Visibility = Visibility.Hidden;
      this.ObjectFlowPathPlanningPanel.Height = 0.0;
      this.HandleRedundantSystemSpecificDisplay();
    }
    if (!this.m_taskManager.ContainsWeldOperation || this.m_taskManager.IsObjectFlowMode)
    {
      this.PreProcessingPanel.Visibility = Visibility.Hidden;
      this.PreProcessingPanel.Height = 0.0;
      this.ApproachDepartMakerPanel.Visibility = Visibility.Hidden;
      this.ApproachDepartMakerPanel.Height = 0.0;
    }
    this.ClearProgressBars();
    this.SetActiveSection();
  }

  private void SelectCbOptimizationTypeFromOption(KiAppOptimizationOption option)
  {
    foreach (object obj in (IEnumerable) this.cbOptimizationType.Items)
    {
      if (obj is CApAPPOptimizationComboBoxItem optimizationComboBoxItem && optimizationComboBoxItem.OptimizationOption == option)
      {
        this.cbOptimizationType.SelectedItem = (object) optimizationComboBoxItem;
        break;
      }
    }
  }

  private void HandleRedundantSystemSpecificDisplay()
  {
    bool flag = true;
    for (int index = 0; index < this.m_taskManager.CountTasks(); ++index)
    {
      if (this.m_taskManager.Tasks[index] is CApAPPRoboticTask && !(this.m_taskManager.Tasks[index] as CApAPPRoboticTask).IsRedundantSystemTask())
      {
        flag = false;
        break;
      }
    }
    if (!flag)
      return;
    this.cbCheckCableTwisting.Visibility = Visibility.Collapsed;
    this.spMaxJ4J6.Visibility = Visibility.Collapsed;
  }

  public string UnitFormat
  {
    get => "F" + TxApplication.Options.Units.LinearDigitsAfterDecimalPoint.ToString();
  }

  private void InitClearanceOptimizationData()
  {
    this.m_clearanceOptimDataList = new List<CApAPPClearanceOptimizationCollisionSetData>();
    TxCollisionRoot collisionRoot = TxApplication.ActiveDocument.CollisionRoot;
    for (int index = 0; index < collisionRoot.Pairs.Count; ++index)
    {
      TxCollisionPair pair = collisionRoot.Pairs[index] as TxCollisionPair;
      if (pair.Active)
      {
        double num = pair.IsNearMissDefined ? pair.NearMissDistance : collisionRoot.NearMissDefaultValue;
        this.m_clearanceOptimDataList.Add(new CApAPPClearanceOptimizationCollisionSetData(pair.Name, num, num));
      }
    }
    if (this.m_pathPlanningParams.CollisionSetDesiredClearances.Length == this.m_clearanceOptimDataList.Count)
    {
      for (int index = 0; index < this.m_clearanceOptimDataList.Count; ++index)
        this.m_clearanceOptimDataList[index].DesiredClearanceValue = this.m_pathPlanningParams.CollisionSetDesiredClearances[index] <= this.m_clearanceOptimDataList[index].NearMissValue ? this.m_clearanceOptimDataList[index].NearMissValue : this.m_pathPlanningParams.CollisionSetDesiredClearances[index];
    }
    this.fgDesiredClearances.Columns[2].HeaderStringFormat = "F2";
    if (this.m_clearanceOptimDataList == null)
      return;
    this.fgDesiredClearances.ItemsSource = (IEnumerable) null;
    this.fgDesiredClearances.ItemsSource = (IEnumerable) this.m_clearanceOptimDataList;
    this.fgDesiredClearances.Refresh();
  }

  private void DisplayInitErrors()
  {
    CApAPPInitErrorDisplayer initErrorDisplayer = new CApAPPInitErrorDisplayer(this.m_taskManager, this.m_wasIgnoreLogicOLPCommands);
    bool shouldContinue = false;
    initErrorDisplayer.Display(ref shouldContinue);
    this.IsUnknowErrorDisplayed = initErrorDisplayer.IsUnknowZoneNamesError;
    this.ShouldBeStarted = shouldContinue;
  }

  private void DisplayBlockingInitErrors()
  {
    CApAPPInitErrorDisplayer initErrorDisplayer = new CApAPPInitErrorDisplayer(this.m_taskManager, this.m_wasIgnoreLogicOLPCommands);
    if (!initErrorDisplayer.AreTasksInvalid)
      return;
    bool shouldContinue = false;
    initErrorDisplayer.Display(ref shouldContinue);
    this.ShouldBeStarted = shouldContinue;
  }

  private void RegisterSimulationEvents()
  {
    TxApplication.ActiveDocument.SimulationPlayer.SimulationStartedForward += new TxSimulationPlayer_SimulationStartedForwardEventHandler(this.SimulationPlayer_SimulationStartedForward);
    TxApplication.ActiveDocument.SimulationPlayer.SimulationStartedBackward += new TxSimulationPlayer_SimulationStartedBackwardEventHandler(this.SimulationPlayer_SimulationStartedBackward);
    TxApplication.ActiveDocument.SimulationPlayer.SimulationEndedForward += new TxSimulationPlayer_SimulationEndedForwardEventHandler(this.SimulationPlayer_SimulationEndedForward);
    TxApplication.ActiveDocument.SimulationPlayer.SimulationEndedBackward += new TxSimulationPlayer_SimulationEndedBackwardEventHandler(this.SimulationPlayer_SimulationEndedBackward);
    TxApplication.ActiveDocument.SimulationPlayer.SimulationStopped += new TxSimulationPlayer_SimulationStoppedEventHandler(this.SimulationPlayer_SimulationStopped);
  }

  private void UnregisterSimulationEvents()
  {
    TxApplication.ActiveDocument.SimulationPlayer.SimulationStartedForward -= new TxSimulationPlayer_SimulationStartedForwardEventHandler(this.SimulationPlayer_SimulationStartedForward);
    TxApplication.ActiveDocument.SimulationPlayer.SimulationStartedBackward -= new TxSimulationPlayer_SimulationStartedBackwardEventHandler(this.SimulationPlayer_SimulationStartedBackward);
    TxApplication.ActiveDocument.SimulationPlayer.SimulationEndedForward -= new TxSimulationPlayer_SimulationEndedForwardEventHandler(this.SimulationPlayer_SimulationEndedForward);
    TxApplication.ActiveDocument.SimulationPlayer.SimulationEndedBackward -= new TxSimulationPlayer_SimulationEndedBackwardEventHandler(this.SimulationPlayer_SimulationEndedBackward);
    TxApplication.ActiveDocument.SimulationPlayer.SimulationStopped -= new TxSimulationPlayer_SimulationStoppedEventHandler(this.SimulationPlayer_SimulationStopped);
  }

  private void SimulationPlayer_SimulationEndedBackward(
    object sender,
    TxSimulationPlayer_SimulationEndedBackwardEventArgs args)
  {
    if (this.m_currentPlanType != CUiAPPMainWindow.PlanType.NONE)
      return;
    this.UpdateAllPlanningButtonVisibility(true);
  }

  private void SimulationPlayer_SimulationEndedForward(
    object sender,
    TxSimulationPlayer_SimulationEndedForwardEventArgs args)
  {
    if (this.m_currentPlanType != CUiAPPMainWindow.PlanType.NONE)
      return;
    this.UpdateAllPlanningButtonVisibility(true);
  }

  private void SimulationPlayer_SimulationStartedBackward(
    object sender,
    TxSimulationPlayer_SimulationStartedBackwardEventArgs args)
  {
    if (this.m_currentPlanType != CUiAPPMainWindow.PlanType.NONE)
      return;
    this.UpdateAllPlanningButtonVisibility(false);
  }

  private void SimulationPlayer_SimulationStartedForward(
    object sender,
    TxSimulationPlayer_SimulationStartedForwardEventArgs args)
  {
    if (this.m_currentPlanType != CUiAPPMainWindow.PlanType.NONE)
      return;
    this.UpdateAllPlanningButtonVisibility(false);
  }

  private void SimulationPlayer_SimulationStopped(
    object sender,
    TxSimulationPlayer_SimulationStoppedEventArgs args)
  {
    if (this.m_currentPlanType != CUiAPPMainWindow.PlanType.NONE)
      return;
    this.UpdateAllPlanningButtonVisibility(true);
  }

  private void fg_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    int selectedIndex = ((Selector) sender).SelectedIndex;
    if (selectedIndex == -1)
      return;
    this.m_locationsGrid.SelectionChanged(selectedIndex);
  }

  private void tbClearanceOpt_PreviewTextInput(object sender, TextCompositionEventArgs e)
  {
    string text = e.Text;
    double result = 0.0;
    if (double.TryParse(text, out result) || !(text != ",") || !(text != "."))
      return;
    e.Handled = true;
  }

  private void m_ctoEnableTimeLimitLabelNewFull_Click(object sender, RoutedEventArgs e)
  {
    bool flag = this.m_ctoEnableTimeLimitLabelNewFull.IsChecked.Value;
    this.m_pathPlanningParams.IsOptimizationTimeLimitEnabled = flag;
    ((UIElement) this.TxNumericEditBoxOptimizationTimeLimitNewFull).IsEnabled = flag;
  }

  private void m_ctoEnableTargetCycleTime_Click(object sender, RoutedEventArgs e)
  {
    bool flag = this.m_ctoEnableTargetCycleTime.IsChecked.Value;
    this.m_pathPlanningParams.IsOptimizationCycleTimeTargetEnabled = flag;
    ((UIElement) this.TxNumericEditBoxOptimizationCycleTimeTarget).IsEnabled = flag;
  }

  private void ctmActiveAllLocations_ItemClicked(object sender, RoutedEventArgs e)
  {
    for (int index = 0; index < this.m_taskManager.CountTasks(); ++index)
    {
      if (this.m_taskManager.Tasks[index].CountWaypoints() > 0)
        this.m_taskManager.Tasks[index].SetActiveRange(0, this.m_taskManager.Tasks[index].CountWaypoints() - 1);
    }
    this.m_locationsGrid.RefreshAll();
  }

  private void ctmActiveSelectedLocations_ItemClicked(object sender, RoutedEventArgs e)
  {
    IList selectedItems = this.fgLocationGrid.SelectedItems;
    if (selectedItems.Count >= 2)
    {
      int waypointRank1 = (selectedItems[0] as CApAPPWaypoint).WaypointRank;
      int waypointRank2 = (selectedItems[selectedItems.Count - 1] as CApAPPWaypoint).WaypointRank;
      CApAPPTask task1 = (selectedItems[0] as CApAPPWaypoint).Task;
      (selectedItems[0] as CApAPPWaypoint).Task.SetActiveRange(waypointRank1, waypointRank2);
      (selectedItems[0] as CApAPPWaypoint).Task.ClearWaypointPlanSuccess();
      foreach (CApAPPTask task2 in this.m_taskManager.Tasks)
      {
        if (task2 != task1)
          task2.DeactivateAllRanges();
      }
    }
    this.m_locationsGrid.RefreshAll();
  }

  private void ctmLinearMotion_ItemClicked(object sender, RoutedEventArgs e)
  {
    IList selectedItems = this.fgLocationGrid.SelectedItems;
    if (selectedItems.Count < 1)
      return;
    for (int index = 0; index < selectedItems.Count; ++index)
      (selectedItems[index] as CApAPPWaypoint).MotionType = CApAPPMotionType.LinearMotion;
  }

  private void ctmJointMotion_ItemClicked(object sender, RoutedEventArgs e)
  {
    IList selectedItems = this.fgLocationGrid.SelectedItems;
    if (selectedItems.Count < 1)
      return;
    for (int index = 0; index < selectedItems.Count; ++index)
      (selectedItems[index] as CApAPPWaypoint).MotionType = CApAPPMotionType.JointMotion;
  }

  private void ctmSkipSegment_ItemClicked(object sender, RoutedEventArgs e)
  {
    CApAPPWaypoint selectedItem = this.fgLocationGrid.SelectedItem as CApAPPWaypoint;
    if (this.m_planManager == null)
      return;
    this.m_planManager.SkipPlanning(selectedItem);
  }

  private void ctmStopAllPlanning_ItemClicked(object sender, RoutedEventArgs e)
  {
    if (this.m_planManager == null)
      return;
    this.m_planManager.StopPlanning();
  }

  private void UpdatePlanOptDoBothButtonsWidth(object sender, SizeChangedEventArgs e)
  {
    double num = Math.Max(this.btnPlanAndOptimize.ActualWidth, Math.Max(this.btnPlan.ActualWidth, Math.Max(this.btnOptimize.ActualWidth, 0.0)));
    this.btnOptimize.MinWidth = num;
    this.btnPlan.MinWidth = num;
    this.btnPlanAndOptimize.MinWidth = num;
  }

  private void ctmOpening(object sender, ContextMenuEventArgs e)
  {
    ItemCollection items = this.fgContextMenu.Items;
    items.Clear();
    if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.NONE)
    {
      System.Windows.Controls.MenuItem newItem1 = new System.Windows.Controls.MenuItem();
      newItem1.Header = (object) StringTable.AUTO_PATH_PLAN_ACTIVATE_ALL_LOCATIONS_ITEM;
      newItem1.Click += new RoutedEventHandler(this.ctmActiveAllLocations_ItemClicked);
      items.Add((object) newItem1);
      System.Windows.Controls.MenuItem newItem2 = new System.Windows.Controls.MenuItem();
      newItem2.Header = (object) StringTable.AUTO_PATH_PLAN_ACTIVATE_SELECTED_LOCATIONS_ITEM;
      newItem2.Click += new RoutedEventHandler(this.ctmActiveSelectedLocations_ItemClicked);
      items.Add((object) newItem2);
      items.Add((object) new Separator());
      System.Windows.Controls.MenuItem newItem3 = new System.Windows.Controls.MenuItem();
      newItem3.Header = (object) StringTable.AUTO_PATH_PLAN_LINEAR_MOTION_ITEM;
      newItem3.Click += new RoutedEventHandler(this.ctmLinearMotion_ItemClicked);
      items.Add((object) newItem3);
      System.Windows.Controls.MenuItem newItem4 = new System.Windows.Controls.MenuItem();
      newItem4.Header = (object) StringTable.AUTO_PATH_PLAN_JOINT_MOTION_ITEM;
      newItem4.Click += new RoutedEventHandler(this.ctmJointMotion_ItemClicked);
      items.Add((object) newItem4);
      if (this.fgLocationGrid.SelectedItems.Count < 2)
      {
        newItem2.IsEnabled = false;
      }
      else
      {
        IList selectedItems = this.fgLocationGrid.SelectedItems;
        if ((selectedItems[0] as CApAPPWaypoint).Task == (selectedItems[selectedItems.Count - 1] as CApAPPWaypoint).Task)
          return;
        newItem2.IsEnabled = false;
      }
    }
    else
    {
      System.Windows.Controls.MenuItem newItem5 = new System.Windows.Controls.MenuItem();
      newItem5.Header = (object) StringTable.AUTO_PATH_PLAN_SKIP_SEGMENT_ITEM;
      newItem5.Click += new RoutedEventHandler(this.ctmSkipSegment_ItemClicked);
      items.Add((object) newItem5);
      System.Windows.Controls.MenuItem newItem6 = new System.Windows.Controls.MenuItem();
      newItem6.Header = (object) StringTable.AUTO_PATH_PLAN_STOP_ALL_PLANNINGS_ITEM;
      newItem6.Click += new RoutedEventHandler(this.ctmStopAllPlanning_ItemClicked);
      items.Add((object) newItem6);
    }
  }

  protected virtual void OnClosing(CancelEventArgs e)
  {
    this.RestoreLogicOLPCommands();
    this.RestoreSimulationFixer();
    this.SaveParameters();
    base.OnClosing(e);
  }

  public void btnPlanAndOpt_Click(object sender, RoutedEventArgs e)
  {
    if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.NONE)
    {
      if (!this.DoesUserAllowEnergyOptimizationWithInconsistentZone())
        return;
      this.m_currentPlanType = CUiAPPMainWindow.PlanType.PLAN_AND_OPTIMIZATION;
      this.StartPathPlanning();
    }
    else
    {
      if (this.m_planManager == null)
        return;
      this.m_planManager.StopPlanning();
    }
  }

  public void btnMagnetPoint_Click(object sender, RoutedEventArgs e)
  {
    if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.NONE || this.m_planManager == null)
      return;
    this.m_planManager.ToggleMagnetPoint();
    bool? isChecked = this.btnMagnetPoint.IsChecked;
    bool flag = true;
    if (isChecked.GetValueOrDefault() == flag & isChecked.HasValue)
    {
      this.cbUpdateDisplay.IsEnabled = false;
      this.m_wasUpdateDisplayEnabledBeforeMagnetPoint = this.m_isUpdateDisplayEnabled;
      this.IsUpdateDisplayEnabled = true;
    }
    else
    {
      this.cbUpdateDisplay.IsEnabled = true;
      this.IsUpdateDisplayEnabled = this.m_wasUpdateDisplayEnabledBeforeMagnetPoint;
    }
    this.m_analytics.HasMagnetPointBeenUsed = true;
  }

  private void btnResetMagnetPoint_Click(object sender, RoutedEventArgs e)
  {
    if (this.m_planManager == null)
      return;
    this.m_planManager.SetMagnetPointPositionToLastAddedNode();
  }

  public void btnPlan_Click(object sender, RoutedEventArgs e)
  {
    if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.NONE)
    {
      this.m_currentPlanType = CUiAPPMainWindow.PlanType.PLAN;
      this.StartPathPlanning();
      if (this.m_isUpdateDisplayEnabled)
        this.m_planManager.EnableShowLastAddedPosition();
      else
        this.m_planManager.DisableShowLastAddedPosition();
    }
    else
    {
      this.btnPlan.IsEnabled = false;
      if (this.m_planManager == null)
        return;
      if (this.m_planManager.IsMagnetPointEnabled())
      {
        this.m_planManager.ToggleMagnetPoint();
        this.cbUpdateDisplay.IsEnabled = true;
        this.IsUpdateDisplayEnabled = this.m_wasUpdateDisplayEnabledBeforeMagnetPoint;
      }
      this.m_planManager.StopPlanning();
    }
  }

  public void btnOptimize_Click(object sender, RoutedEventArgs e)
  {
    if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.NONE)
    {
      if (!this.DoesUserAllowEnergyOptimizationWithInconsistentZone())
        return;
      this.m_currentPlanType = CUiAPPMainWindow.PlanType.OPTIMIZATION;
      this.StartPathPlanning();
    }
    else
    {
      if (this.m_planManager == null)
        return;
      this.m_planManager.StopPlanning();
    }
  }

  private void cbConsiderActiveSection_Click(object sender, RoutedEventArgs e)
  {
    bool flag = this.cbConsiderActiveSection.IsChecked.Value;
    this.m_pathPlanningParams.SectionIsActivated = flag;
    this.cbIncludeDevice.IsEnabled = flag && !this.m_taskManager.IsObjectFlowMode;
    this.SetActiveSection();
  }

  private void cbIncludeDevice_Click(object sender, RoutedEventArgs e)
  {
    this.m_pathPlanningParams.IncludeDeviceInActiveSection = this.cbIncludeDevice.IsChecked.Value;
    this.SetActiveSection();
  }

  private void cbCheckCableTwisting_Click(object sender, RoutedEventArgs e)
  {
    bool flag = this.cbCheckCableTwisting.IsChecked.Value;
    this.m_pathPlanningParams.CheckCableTwistingIsActivated = flag;
    this.spMaxJ4J6.IsEnabled = flag;
    this.UpdateCableTwistingChecking();
  }

  private void tbMaxJ4J6Value_TextChanged(object sender, TextChangedEventArgs e)
  {
    if (!(this.tbMaxJ4J6Value.Text != ""))
      return;
    try
    {
      this.m_pathPlanningParams.MaxAbsJ4J6 = Convert.ToDouble(this.tbMaxJ4J6Value.Text) * TxApplication.Options.Units.AngularMultiplier;
      this.UpdateCableTwistingChecking();
    }
    catch (FormatException ex)
    {
      this.tbMaxJ4J6Value.Text = Convert.ToString(this.m_pathPlanningParams.MaxAbsJ4J6 / TxApplication.Options.Units.AngularMultiplier);
    }
    catch (OverflowException ex)
    {
      this.tbMaxJ4J6Value.Text = "0";
    }
  }

  private void tbMaxJ4J6Value_FocusChanged(object sender, DependencyPropertyChangedEventArgs e)
  {
    if (!(this.tbMaxJ4J6Value.Text == ""))
      return;
    this.tbMaxJ4J6Value.Text = Convert.ToString(this.m_pathPlanningParams.MaxAbsJ4J6 / TxApplication.Options.Units.AngularMultiplier);
  }

  private void tbMaxJ4J6Value_PreviewTextInput(object sender, TextCompositionEventArgs e)
  {
    string text = e.Text;
    int result = 0;
    if (int.TryParse(text, out result))
      return;
    e.Handled = true;
  }

  private void cbActivatedExtraction_Click(object sender, RoutedEventArgs e)
  {
    this.m_pathPlanningParams.ExtractionIsActivated = this.cbActivatedExtraction.IsChecked.Value;
  }

  private void cbQuality_DropdownClosed(object sender, EventArgs e)
  {
    if (this.cbQuality.Text == CApAPPMainWindowStringTable.AppPlanningQualityDraft)
    {
      this.m_pathPlanningParams.Quality = (KiAppPathPlanningQuality) 0;
    }
    else
    {
      if (!(this.cbQuality.Text == CApAPPMainWindowStringTable.AppPlanningQualityExact))
        return;
      this.m_pathPlanningParams.Quality = (KiAppPathPlanningQuality) 1;
    }
  }

  private void cbOptimization_DropdownClosed(object sender, EventArgs e)
  {
    if (!(this.cbOptimizationType.SelectedItem is CApAPPOptimizationComboBoxItem selectedItem))
      return;
    this.m_pathPlanningParams.OptimizationOption = selectedItem.OptimizationOption;
    this.OptimizationChanged();
  }

  private void btnCancel_Click(object sender, RoutedEventArgs e)
  {
    double actualHeight = this.fgLocationGrid.ActualHeight;
    this.Undo();
    this.m_locationsGrid.UpdateView();
    this.m_locationsGrid.SelectAllExternalOperations();
    if (this.m_oldRealHeight != 0.0)
    {
      this.m_oldRealHeight += this.fgLocationGrid.ActualHeight - actualHeight;
      if (this.m_oldRealHeight < SystemParameters.WorkArea.Height)
      {
        ((FrameworkElement) this).MinHeight = this.m_oldRealHeight;
        ((FrameworkElement) this).MaxHeight = this.m_oldRealHeight;
      }
    }
    else
    {
      // ISSUE: explicit non-virtual call
      if (__nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight) > SystemParameters.WorkArea.Height)
      {
        // ISSUE: explicit non-virtual call
        this.m_oldRealHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
        ((FrameworkElement) this).MinHeight = SystemParameters.WorkArea.Height;
        ((FrameworkElement) this).MaxHeight = SystemParameters.WorkArea.Height;
      }
      else
      {
        // ISSUE: explicit non-virtual call
        ((FrameworkElement) this).MinHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
        // ISSUE: explicit non-virtual call
        ((FrameworkElement) this).MaxHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
      }
    }
    if (!this.LimitsUserControl.IsInitialized)
      return;
    this.LimitsUserControl.UpdateLimitError();
  }

  private void onRestoreDefaultTriggered(object sender, EventArgs e)
  {
    this.m_pathPlanningParams.SetParameters(this.m_defaultPathPlanningParams);
    if (this.m_taskManager.IsObjectFlowMode)
      this.LimitsUserControl.Restore();
    for (int index = 0; index < this.m_taskManager.CountTasks(); ++index)
    {
      if (this.m_taskManager.Tasks[index] is CApAPPRoboticTask)
      {
        (this.m_taskManager.Tasks[index] as CApAPPRoboticTask).SetDefaultDrivingJointsWeights();
        (this.m_taskManager.Tasks[index] as CApAPPRoboticTask).SetDefaultZoneNames();
      }
    }
    this.InitDialog();
    if (!this.LimitsUserControl.IsInitialized)
      return;
    this.LimitsUserControl.UpdateLimitError();
  }

  private void SaveParameters()
  {
    this.UpdateParameters();
    if (this.m_parameterController == null)
      return;
    this.m_parameterController.Save();
  }

  private void btnOK_Click(object sender, RoutedEventArgs e)
  {
    this.SaveParameters();
    if (this.m_taskManager.IsObjectFlowMode)
      this.UnregisterObjectFlowAbsoluteLocationChangedEvent();
    this.m_locationsGrid.SelectAllExternalOperations();
    this.m_taskManager.Clear();
    ((Window) this).Close();
  }

  private void m_planCommand_PlanningDidProgress(
    object sender,
    CApAPPPlanCommandBase.PlanDidProgressEventArgs args)
  {
    this.UpdateProgressUI(args.TimeInSecond, args.Progress);
    this.UpdatePathPlanningStatusUI();
  }

  private void m_planCommand_PlanningDidUpdate(object sender, EventArgs args)
  {
    double actualHeight = this.fgLocationGrid.ActualHeight;
    this.m_locationsGrid.UpdateView();
    if (this.m_oldRealHeight != 0.0)
    {
      this.m_oldRealHeight += this.fgLocationGrid.ActualHeight - actualHeight;
      if (this.m_oldRealHeight >= SystemParameters.WorkArea.Height)
        return;
      ((FrameworkElement) this).MinHeight = this.m_oldRealHeight;
      ((FrameworkElement) this).MaxHeight = this.m_oldRealHeight;
    }
    else
    {
      // ISSUE: explicit non-virtual call
      double num = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
      Rect workArea = SystemParameters.WorkArea;
      double height = workArea.Height;
      if (num > height)
      {
        // ISSUE: explicit non-virtual call
        this.m_oldRealHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
        workArea = SystemParameters.WorkArea;
        ((FrameworkElement) this).MinHeight = workArea.Height;
        workArea = SystemParameters.WorkArea;
        ((FrameworkElement) this).MaxHeight = workArea.Height;
      }
      else
      {
        // ISSUE: explicit non-virtual call
        ((FrameworkElement) this).MinHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
        // ISSUE: explicit non-virtual call
        ((FrameworkElement) this).MaxHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
      }
    }
  }

  private void m_planCommand_PlanningDidEnd(
    object sender,
    CApAPPPlanCommandBase.PlanSuccessEventArgs e)
  {
    this.SendComputationEndAnalytics(e);
    this.m_currentPlanType = CUiAPPMainWindow.PlanType.NONE;
    TxApplication.ActiveDocument.CollisionRoot.CheckCollisions = this.m_wasCollisionCheckEnabledBeforePlanning;
    this.ReactivateSimulationRefreshMode();
    this.UpdateDialogAfterPlanning();
    if (e.Successful)
    {
      if (this.PathPlanningParams.OptimizationOption == 3)
        this.ShowEnergyGain();
      else if (this.PathPlanningParams.OptimizationOption == 2 && this.PathPlanningParams.CTOMode == 1)
      {
        this.ShowCTOGain();
      }
      else
      {
        if (this.PathPlanningParams.OptimizationOption != 2 || this.PathPlanningParams.CTOMode != 2)
          return;
        this.ShowCTOResult();
      }
    }
    else
    {
      this.m_planManager.PlanCommand.AfterPlanningFailure();
      this.ShowErrorMessage(e.ErrorMessage, e.ErrorDetails);
      foreach (CApAPPTask task in this.m_taskManager.Tasks)
        task.RestoreInitialState();
      this.RemoveCurrentBackUpOperations();
    }
  }

  private void SendComputationEndAnalytics(CApAPPPlanCommandBase.PlanSuccessEventArgs e)
  {
    CApAPPAnalytics.ComputationType planType = CApAPPAnalytics.ComputationType.PathPlanning;
    switch (this.m_currentPlanType)
    {
      case CUiAPPMainWindow.PlanType.PLAN:
        planType = CApAPPAnalytics.ComputationType.PathPlanning;
        break;
      case CUiAPPMainWindow.PlanType.OPTIMIZATION:
        planType = CApAPPAnalytics.ComputationType.Optimization;
        break;
      case CUiAPPMainWindow.PlanType.PLAN_AND_OPTIMIZATION:
        planType = CApAPPAnalytics.ComputationType.DoBoth;
        break;
    }
    double trajectoryOptimizationGain = 0.0;
    if (this.m_planManager.PlanCommand is CApAPPOptimizeCycleTimeCommand)
    {
      IList<Tuple<CApAPPTask, double>> fitnessGainPerTask = (this.m_planManager.PlanCommand as CApAPPOptimizeCycleTimeCommand).GetFullCTOFitnessGainPerTask();
      if (fitnessGainPerTask.Count > 0)
        trajectoryOptimizationGain = fitnessGainPerTask[0].Item2;
    }
    int zoneCount = 0;
    if (this.m_taskManager.Tasks.Count > 0 && this.m_taskManager.Tasks[0] is CApAPPRoboticTask)
      zoneCount = Math.Max((this.m_taskManager.Tasks[0] as CApAPPRoboticTask).JointMotionZoneNames.Length, (this.m_taskManager.Tasks[0] as CApAPPRoboticTask).LinearMotionZoneNames.Length);
    int fixedPointCount = 0;
    foreach (CApAPPWaypoint waypoint in this.m_taskManager.Tasks[0].Waypoints())
    {
      if (waypoint.Locked || waypoint.Fixed)
        ++fixedPointCount;
    }
    this.m_analytics.LogComputationEnd(this.m_planManager.PlanCommand.GetElapsedTime(), planType, this.m_pathPlanningParams, zoneCount, trajectoryOptimizationGain, e.Successful ? CApAPPAnalytics.Status.Success : CApAPPAnalytics.Status.Failure, this.LimitsUserControl, fixedPointCount);
  }

  private void m_planCommand_WaypointDidChanged(object sender, EventArgs e)
  {
    this.m_locationsGrid.Refresh(CApAPPWaypointProperty.Status);
  }

  private void m_cappPlanCommand_PlanningWillEnd(object sender, EventArgs e)
  {
    this.btnPlan.IsEnabled = false;
    this.btnOptimize.IsEnabled = false;
    this.btnPlanAndOptimize.IsEnabled = false;
  }

  private void StartUndoTransaction() => TxApplication.ActiveUndoManager.StartTransaction();

  private void EndUndoTransaction() => TxApplication.ActiveUndoManager.EndTransaction();

  public virtual void Undo()
  {
    for (int index = 0; index < this.m_originalWaypointList.Count; ++index)
    {
      this.m_taskManager.Tasks[index].Waypoints(this.m_originalWaypointList[index]);
      this.m_taskManager.Tasks[index].UpdateTxOperation(true);
      this.m_taskManager.Tasks[index].UpdateWaypointsStatus();
      this.m_taskManager.Tasks[index].RestoreInitialState();
    }
    this.RemoveCurrentBackUpOperations();
  }

  private void AllPanningButtonSensitivity(bool enable)
  {
    this.btnPlan.IsEnabled = enable;
    this.btnOptimize.IsEnabled = enable;
    this.btnPlanAndOptimize.IsEnabled = enable;
  }

  private bool DoesUserAllowEnergyOptimizationWithInconsistentZone()
  {
    bool flag = true;
    if (((this.cbOptimizationType.SelectedItem as CApAPPOptimizationComboBoxItem).OptimizationType == CApAPPPlanningType.ENERGY_OPT || (this.cbOptimizationType.SelectedItem as CApAPPOptimizationComboBoxItem).OptimizationType == CApAPPPlanningType.CYCLETIME_OPT) && !this.IsUnknowErrorDisplayed)
    {
      switch (this.CheckEnergyAndCycleTimeConsistantZones())
      {
        case CUiAPPMainWindow.EnergyCycleTimeZoneValidity.UNKNOWN_ZONE:
          if (TxMessageBox.Show(CApAPPMainWindowStringTable.EnergyOptimizationUnknownZoneWarningMessage, CApAPPMainWindowStringTable.EnergyOptimizationInvalidZoneWarningTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
          {
            flag = false;
            break;
          }
          break;
        case CUiAPPMainWindow.EnergyCycleTimeZoneValidity.INVALID_ZONE:
          if (TxMessageBox.Show(CApAPPMainWindowStringTable.EnergyOptimizationInvalidZoneWarningMessage, CApAPPMainWindowStringTable.EnergyOptimizationInvalidZoneWarningTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
          {
            flag = false;
            break;
          }
          break;
        default:
          flag = true;
          break;
      }
    }
    return flag;
  }

  private CUiAPPMainWindow.EnergyCycleTimeZoneValidity CheckEnergyAndCycleTimeConsistantZones()
  {
    CUiAPPMainWindow.EnergyCycleTimeZoneValidity timeZoneValidity = CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE;
    foreach (CApAPPTask task in this.m_taskManager.Tasks)
      timeZoneValidity = this.CheckEnergyAndCycleTimeConsistantZones(task as CApAPPRoboticTask);
    return timeZoneValidity;
  }

  private CUiAPPMainWindow.EnergyCycleTimeZoneValidity CheckEnergyAndCycleTimeConsistantZones(
    CApAPPRoboticTask roboticTask)
  {
    List<string> zoneParameters = CApAPPUtilities.GetZoneParameters(roboticTask.Robot, roboticTask.Operation);
    CUiAPPMainWindow.EnergyCycleTimeZoneValidity timeZoneValidity = this.CheckEnergyAndCycleTimeConsistantZones(roboticTask, zoneParameters, (TxMotionType) 1);
    if (timeZoneValidity == CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE)
      timeZoneValidity = this.CheckEnergyAndCycleTimeConsistantZones(roboticTask, zoneParameters, (TxMotionType) 2);
    return timeZoneValidity;
  }

  public CUiAPPMainWindow.EnergyCycleTimeZoneValidity CheckEnergyAndCycleTimeConsistantZones(
    CApAPPRoboticTask roboticTask,
    List<string> zoneParameterNames,
    TxMotionType motionType)
  {
    CUiAPPMainWindow.EnergyCycleTimeZoneValidity timeZoneValidity = CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE;
    string[][] motionZoneNames = roboticTask.GetMotionZoneNames(motionType);
    ArrayList initialZones = roboticTask.GetInitialZones(roboticTask.Operation as ITxRoboticOperation);
    int num = 0;
    foreach (string zoneParameterName in zoneParameterNames)
    {
      List<string> zoneParameterValues = CApAPPUtilities.GetAllowableZoneParameterValues(roboticTask.Robot, roboticTask.Operation, zoneParameterName, motionType);
      timeZoneValidity = this.CheckEnergyAndCycleTimeConsistantZones(roboticTask, initialZones, motionZoneNames, zoneParameterValues, motionType);
      if (timeZoneValidity == CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE)
        ++num;
      else
        break;
    }
    return timeZoneValidity;
  }

  public CUiAPPMainWindow.EnergyCycleTimeZoneValidity CheckEnergyAndCycleTimeConsistantZones(
    CApAPPRoboticTask roboticTask,
    ArrayList taskZones,
    string[][] iparameterZones,
    List<string> allowableZones,
    TxMotionType motionType)
  {
    CUiAPPMainWindow.EnergyCycleTimeZoneValidity timeZoneValidity = CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE;
    List<List<string>> stringListList = CApAPPUtilities.ConvertZoneInZoneList(iparameterZones);
    List<List<string>> itaskZoneList = CApAPPUtilities.ConvertZoneInZoneList(taskZones);
    if (stringListList.Count != 0)
    {
      for (int index = 0; index < stringListList.Count && timeZoneValidity == CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE; ++index)
      {
        timeZoneValidity = this.IsZoneValid(CApAPPUtilities.GetZoneIndex(stringListList[index][stringListList[index].Count - 1], allowableZones), roboticTask, itaskZoneList, allowableZones, motionType);
        if (timeZoneValidity != CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE)
          break;
      }
    }
    return timeZoneValidity;
  }

  public CUiAPPMainWindow.EnergyCycleTimeZoneValidity IsZoneValid(
    int parameterZonesIndex,
    CApAPPRoboticTask roboticTask,
    List<List<string>> itaskZoneList,
    List<string> allowableZones,
    TxMotionType motionType)
  {
    CUiAPPMainWindow.EnergyCycleTimeZoneValidity timeZoneValidity = CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE;
    for (int index1 = 0; index1 < itaskZoneList.Count && timeZoneValidity == CUiAPPMainWindow.EnergyCycleTimeZoneValidity.VALID_ZONE; ++index1)
    {
      if (itaskZoneList[index1].Count == roboticTask.Waypoints().Count)
      {
        for (int index2 = 0; index2 < itaskZoneList[index1].Count; ++index2)
        {
          if (roboticTask.Waypoints()[index2].MotionType == CApAPPMotionType.JointMotion && motionType == 1 || roboticTask.Waypoints()[index2].MotionType == CApAPPMotionType.LinearMotion && motionType == 2)
          {
            int zoneIndex = CApAPPUtilities.GetZoneIndex(itaskZoneList[index1][index2], allowableZones);
            if (zoneIndex == -1)
            {
              timeZoneValidity = CUiAPPMainWindow.EnergyCycleTimeZoneValidity.UNKNOWN_ZONE;
              break;
            }
            if (zoneIndex > parameterZonesIndex)
            {
              timeZoneValidity = CUiAPPMainWindow.EnergyCycleTimeZoneValidity.INVALID_ZONE;
              break;
            }
          }
        }
      }
    }
    return timeZoneValidity;
  }

  private void BeforeLaunchPlanning()
  {
    if (this.m_pathPlanningParams.BackUpOperationIsActivated)
      this.BackupOperations();
    this.UpdateParameters();
    this.UpdateDialogBeforeLaunchPlanning();
    this.m_wasCollisionCheckEnabledBeforePlanning = TxApplication.ActiveDocument.CollisionRoot.CheckCollisions;
    this.DeactivateSimulationRefreshMode();
    TxApplication.ActiveDocument.CollisionRoot.CheckCollisions = false;
    TxPerformanceModeEx performanceModeEx = new TxPerformanceModeEx((TxPerformanceModeType) 4);
    TxApplicationEx.PerformanceModeManager().BeginMode(performanceModeEx);
    this.m_analytics.HasMagnetPointBeenUsed = false;
  }

  private void UpdateParameters()
  {
    if (this.m_clearanceOptimDataList != null)
    {
      double[] numArray = new double[this.m_clearanceOptimDataList.Count];
      for (int index = 0; index < this.m_clearanceOptimDataList.Count; ++index)
        numArray[index] = this.m_clearanceOptimDataList[index].DesiredClearanceValue;
      this.m_pathPlanningParams.CollisionSetDesiredClearances = numArray;
    }
    if (this.m_fgLocationGrid_clashColumn == null)
      return;
    this.GUIParameters.LocationGrid_ClashColumnWidth = this.m_fgLocationGrid_clashColumn.Width.Value;
    this.GUIParameters.LocationGrid_FixedColumnWidth = this.m_fgLocationGrid_fixedColumn.Width.Value;
    this.GUIParameters.LocationGrid_MotionColumnWidth = this.m_fgLocationGrid_motionColumn.Width.Value;
    this.GUIParameters.LocationGrid_PathAndLocationsColumnWidth = this.m_fgLocationGrid_pathAndLocationColumn.Width.Value;
    this.GUIParameters.LocationGrid_ZoneColumnWidth = this.m_fgLocationGrid_zoneColumn.Width.Value;
  }

  private void StartPathPlanning()
  {
    List<CApAPPPlanningType> capAppPlanningTypeList = new List<CApAPPPlanningType>();
    if (this.ShouldUseKineoForAppPlanning)
    {
      this.AddCustomPlanningTypes(capAppPlanningTypeList);
    }
    else
    {
      if (this.m_wasKineoForAppAvailableOnStartUp)
        this.DisplayKineoForAppUnavailableWarning();
      this.AddRegularPlanningTypes(capAppPlanningTypeList);
    }
    this.BeforeLaunchPlanning();
    this.m_planManager = new CApAPPPlanManager(this.m_taskManager.Tasks, this.m_pathPlanningParams, capAppPlanningTypeList, this.IsPreProcessingActivated);
    this.UpdateDialogBeforePlanning();
    this.m_planManager.Start();
    this.UpdatePathPlanningStatusUI();
  }

  private void AddRegularPlanningTypes(List<CApAPPPlanningType> planningTypes)
  {
    if (this.IsApproachDepartCreationActivated && this.m_currentPlanType != CUiAPPMainWindow.PlanType.OPTIMIZATION)
      planningTypes.Add(CApAPPPlanningType.APPROACH_DEPART_CREATION);
    CApAPPPlanningType capAppPlanningType = CApAPPPlanningType.PATHPLANNING;
    if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.OPTIMIZATION || this.m_currentPlanType == CUiAPPMainWindow.PlanType.PLAN_AND_OPTIMIZATION)
    {
      capAppPlanningType = (this.cbOptimizationType.SelectedItem as CApAPPOptimizationComboBoxItem).OptimizationType;
      if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.PLAN_AND_OPTIMIZATION)
      {
        switch (capAppPlanningType)
        {
          case CApAPPPlanningType.CLEARANCE_OPT:
            capAppPlanningType = CApAPPPlanningType.PATHPLANNING_AND_CLEARANCE_OPT;
            break;
          case CApAPPPlanningType.CYCLETIME_OPT:
            planningTypes.Add(CApAPPPlanningType.PATHPLANNING);
            planningTypes.Add(CApAPPPlanningType.PATHPLANNING_POST_PROCESS);
            capAppPlanningType = CApAPPPlanningType.CYCLETIME_OPT;
            break;
          case CApAPPPlanningType.JOINTTRAVEL_OPT:
            capAppPlanningType = CApAPPPlanningType.PATHPLANNING_AND_JOINTTRAVEL_OPT;
            break;
          case CApAPPPlanningType.ENERGY_OPT:
            planningTypes.Add(CApAPPPlanningType.PATHPLANNING);
            planningTypes.Add(CApAPPPlanningType.PATHPLANNING_POST_PROCESS);
            capAppPlanningType = CApAPPPlanningType.ENERGY_OPT;
            break;
        }
      }
      this.m_pathPlanningParams.MustUseRCSForEnergy = this.m_isRCSEnergyCapable;
      if (capAppPlanningType == CApAPPPlanningType.ENERGY_OPT)
        this.m_pathPlanningParams.CTOMode = (KiAppCTOMode) 1;
    }
    planningTypes.Add(capAppPlanningType);
    if (capAppPlanningType != CApAPPPlanningType.PATHPLANNING && capAppPlanningType != CApAPPPlanningType.JOINTTRAVEL_OPT && capAppPlanningType != CApAPPPlanningType.CLEARANCE_OPT && capAppPlanningType != CApAPPPlanningType.PATHPLANNING_AND_JOINTTRAVEL_OPT && capAppPlanningType != CApAPPPlanningType.PATHPLANNING_AND_CLEARANCE_OPT)
      return;
    planningTypes.Add(CApAPPPlanningType.PATHPLANNING_POST_PROCESS);
  }

  private void AddCustomPlanningTypes(List<CApAPPPlanningType> planningTypes)
  {
    switch (this.KineoForAppPlanningType)
    {
      case CUiAPPKineoForAppPlanningParameters.KineoForAppPlanningType.PATH_SEGMENTS:
        planningTypes.Add(CApAPPPlanningType.CUSTOM_PATH_SEGMENTS_PLANNING);
        break;
      case CUiAPPKineoForAppPlanningParameters.KineoForAppPlanningType.TRAJECTORY_SEGMENTS:
        planningTypes.Add(CApAPPPlanningType.CUSTOM_TRAJECTORY_SEGMENTS_PLANNING);
        break;
      case CUiAPPKineoForAppPlanningParameters.KineoForAppPlanningType.WHOLE_TRAJECTORY:
        planningTypes.Add(CApAPPPlanningType.CUSTOM_WHOLE_TRAJECTORY_PLANNING);
        break;
      default:
        throw new NotImplementedException();
    }
  }

  private void DisplayKineoForAppUnavailableWarning()
  {
    int num = (int) TxMessageBox.ShowModal(CApAPPMainWindowStringTable.KineoForAppUnavailableWarningMessage, CApAPPMainWindowStringTable.KineoForAppUnavailableWarningTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  }

  private void GetOperationBackupScope(
    ITxOperation txOp,
    ref ITxObjectCollection copyScope,
    ref ITxObject duplicatedObject)
  {
    ITxObjectCollection objectCollection;
    switch (txOp)
    {
      case TxTcDiscreteOperation _:
      case TxTcContinuousOperation _:
        objectCollection = txOp as ITxObjectCollection;
        break;
      default:
        objectCollection = ((ITxObject) txOp).Collection;
        break;
    }
    switch (objectCollection)
    {
      case TxCompoundOperation _:
      case TxOperationRoot _:
        duplicatedObject = (ITxObject) txOp;
        copyScope = objectCollection;
        break;
      case ITxTcOperation _:
        if (this.m_taskManager.IsObjectFlowMode)
        {
          duplicatedObject = (ITxObject) txOp;
          copyScope = objectCollection;
          break;
        }
        duplicatedObject = (ITxObject) objectCollection;
        copyScope = ((ITxObject) objectCollection).Collection;
        break;
      case TxTcActivity _:
        TxOperationRoot operationRoot = TxApplication.ActiveDocument.OperationRoot;
        if (!TxOperationRoot.op_Inequality(operationRoot, (ITxObject) null))
          break;
        ITxObject itxObject = (ITxObject) objectCollection;
        bool flag = false;
        while (itxObject != operationRoot && !flag)
        {
          itxObject = (ITxObject) itxObject.Collection;
          if (itxObject is ITxTcOperation)
          {
            flag = true;
            duplicatedObject = itxObject;
            copyScope = itxObject.Collection;
          }
        }
        break;
    }
  }

  private void RemoveCurrentBackUpOperations()
  {
    for (int index = 0; index < this.m_backupOperationlist.Count; ++index)
    {
      ITxTypeFilter itxTypeFilter = (ITxTypeFilter) new TxNoTypeFilter();
      bool canBeDeleted = ((ITxObject) (this.m_backupOperationlist[index] as ITxObjectCollection)).CanBeDeleted;
      (this.m_backupOperationlist[index] as ITxObjectCollection).GetDirectDescendants(itxTypeFilter);
      ((ITxObject) (this.m_backupOperationlist[index] as ITxObjectCollection)).Delete();
    }
    this.m_backupOperationlist.Clear();
    TxApplication.RefreshDisplay();
  }

  private void FixAppearances(ITxOperation copiedOperation, ITxOperation originalOperation)
  {
    TxObjectList allPartAppearances = new TxOperationEx(originalOperation).GetAllPartAppearances();
    for (int index = 0; index < ((Collection<ITxObject>) allPartAppearances).Count; ++index)
      new TxPartPhysicalAppearanceEx(((Collection<ITxObject>) allPartAppearances)[index]).SetOperation(copiedOperation, true);
  }

  private void BackupOperations()
  {
    TxApplicationEx.FireDocumentUpdateStarted();
    foreach (CApAPPTask task in this.m_taskManager.Tasks)
    {
      ITxObject duplicatedObject = (ITxObject) null;
      ITxObjectCollection copyScope = (ITxObjectCollection) null;
      this.GetOperationBackupScope(task.Operation, ref copyScope, ref duplicatedObject);
      if (duplicatedObject != null && copyScope != null)
      {
        TxObjectList txObjectList = new TxObjectList();
        Hashtable hashtable = new Hashtable();
        ((Collection<ITxObject>) txObjectList).Add(duplicatedObject);
        if (copyScope.CanPasteList(txObjectList))
        {
          copyScope.Paste(txObjectList, ref hashtable);
          ITxObject copiedOperation = (ITxObject) hashtable[(object) duplicatedObject];
          if (copiedOperation != null)
          {
            copiedOperation.Name = duplicatedObject.Name + "_backup";
            this.FixAppearances(copiedOperation as ITxOperation, task.Operation);
          }
          this.m_backupOperationlist.Add(copiedOperation as ITxOperation);
        }
      }
    }
    TxApplicationEx.FireDocumentUpdateEnded();
  }

  private void ShowErrorMessage(string message, string details)
  {
    new CUiAPPErrorWindow(message, details, CUiAPPErrorWindow.ButtonState.AbortOnly).ShowDialog(true);
  }

  private void ShowEnergyGain()
  {
    this.ShowFitnessGain(CApAPPMainWindowStringTable.EnergyReductionAfterOptimization, CApAPPMainWindowStringTable.EnergyOptimizationSummary);
  }

  private void ShowCTOGain()
  {
    this.ShowFitnessGain(CApAPPMainWindowStringTable.CycleTimeReductionAfterOptimization, CApAPPMainWindowStringTable.CycleTimeOptimizationSummary);
  }

  private void ShowCTOResult()
  {
    if (!(this.m_planManager.PlanCommand is CApAPPOptimizeCycleTimeCommand planCommand))
      return;
    int num = (int) TxMessageBox.Show(planCommand.BuildEndOptimizationMessage(), CApAPPMainWindowStringTable.CycleTimeOptimizationSummary, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
  }

  private void ShowFitnessGain(string messageHeader, string messageBoxCaption)
  {
    if (!(this.m_planManager.PlanCommand is CApAPPOptimizeCycleTimeCommand))
      return;
    IList<Tuple<CApAPPTask, double>> fitnessGainPerTask = (this.m_planManager.PlanCommand as CApAPPOptimizeCycleTimeCommand).GetFullCTOFitnessGainPerTask();
    IList<Tuple<CApAPPTask, double>> tupleList = (IList<Tuple<CApAPPTask, double>>) new List<Tuple<CApAPPTask, double>>();
    foreach (Tuple<CApAPPTask, double> tuple in (IEnumerable<Tuple<CApAPPTask, double>>) fitnessGainPerTask)
      tupleList.Add(new Tuple<CApAPPTask, double>(tuple.Item1, Math.Round(tuple.Item2 * -100.0, 2)));
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.Append(messageHeader);
    if (tupleList.Count == 1)
    {
      stringBuilder.Append($" {tupleList[0].Item2}%");
    }
    else
    {
      stringBuilder.AppendLine();
      foreach (Tuple<CApAPPTask, double> tuple in (IEnumerable<Tuple<CApAPPTask, double>>) tupleList)
        stringBuilder.AppendLine($"  {tuple.Item1.Name}: {tuple.Item2}%");
    }
    int num = (int) TxMessageBox.Show(stringBuilder.ToString(), messageBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
  }

  private void UpdateProgressUI(double timeInSecond, double progress)
  {
    string timeText = CApAPPUtilities.GetTimeText(timeInSecond);
    double num = progress * 100.0;
    switch (this.m_currentPlanType)
    {
      case CUiAPPMainWindow.PlanType.PLAN:
      case CUiAPPMainWindow.PlanType.APPROACH_DEPART_PLAN:
        this.pgbPlanningProgressBar.Value = num;
        this.tbPlanTime.Text = timeText;
        break;
      case CUiAPPMainWindow.PlanType.OPTIMIZATION:
        this.pgbOptimizationProgressBar.Value = num;
        this.tbOptimizationTime.Text = timeText;
        break;
      case CUiAPPMainWindow.PlanType.PLAN_AND_OPTIMIZATION:
        this.pgbPlanningAndOptimizationProgressBar.Value = num;
        this.tbPlanAndOptimizationTime.Text = timeText;
        break;
    }
  }

  private void UpdatePathPlanningStatusUI()
  {
    if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.NONE || this.m_planManager == null)
    {
      this.PathPlanningStatus = CUiAPPMainWindow.PathPlanningUIStatus.NONE;
    }
    else
    {
      if (this.m_taskManager == null)
        return;
      if (this.m_taskManager.IsObjectFlowMode)
      {
        switch ((int) this.m_planManager.GetCurrentPlanningStep())
        {
          case 0:
            this.PathPlanningStatus = CUiAPPMainWindow.PathPlanningUIStatus.NONE;
            break;
          case 1:
            this.PathPlanningStatus = CUiAPPMainWindow.PathPlanningUIStatus.EXTRACTING;
            break;
          case 2:
            this.PathPlanningStatus = CUiAPPMainWindow.PathPlanningUIStatus.PLANNING;
            break;
          case 3:
          case 4:
          case 5:
            this.PathPlanningStatus = this.m_currentPlanType != CUiAPPMainWindow.PlanType.PLAN ? CUiAPPMainWindow.PathPlanningUIStatus.OPTIMIZING : CUiAPPMainWindow.PathPlanningUIStatus.FINALIZING;
            break;
          default:
            this.PathPlanningStatus = CUiAPPMainWindow.PathPlanningUIStatus.NONE;
            break;
        }
        if (this.PathPlanningStatus != CUiAPPMainWindow.PathPlanningUIStatus.PLANNING)
        {
          this.magnetPointPanel.IsEnabled = false;
          if (this.m_planManager == null || !this.m_planManager.IsMagnetPointEnabled())
            return;
          this.m_planManager.ToggleMagnetPoint();
        }
        else
          this.magnetPointPanel.IsEnabled = !this.m_taskManager.ContainsWeldOperation;
      }
      else if (this.m_currentPlanType == CUiAPPMainWindow.PlanType.OPTIMIZATION)
      {
        if (!(this.m_planManager.PlanCommand is CApAPPOptimizeCycleTimeCommand planCommand))
          return;
        if (this.PathPlanningParams.CTOMode == 2)
        {
          double currentResult = 0.0;
          bool timeOutReached = planCommand.GetTimeOutReached();
          string str = "";
          if (timeOutReached)
            str = CApAPPMainWindowStringTable.OptimizationTimeOutReachedStillComputing;
          if (planCommand.GetCycleTimeResult(ref currentResult))
          {
            CApAPPTask currentTask = planCommand.CurrentTask;
            if (currentTask != null)
              this.StatusMessage = string.Format(CApAPPMainWindowStringTable.OptimizationCurrentResultStatusMessage, (object) currentTask.Name, (object) Math.Round(currentResult, 2));
          }
          else
          {
            CApAPPTask currentTask = planCommand.CurrentTask;
            if (currentTask != null)
              this.StatusMessage = string.Format(CApAPPMainWindowStringTable.OptimizationGettingFirstResult, (object) currentTask.Name);
          }
          this.StatusMessage += str;
        }
        else
        {
          int currentSegmentIndex = -1;
          double currentSegmentGain = 0.0;
          double globalGain = 0.0;
          if (planCommand.GetFitnessGain(ref currentSegmentIndex, ref currentSegmentGain, ref globalGain))
          {
            CApAPPTask currentTask = planCommand.CurrentTask;
            if (currentTask != null && currentSegmentIndex >= 0 && currentSegmentIndex < currentTask.CountSubTasks())
              this.StatusMessage = string.Format(CApAPPMainWindowStringTable.OptimizationGainStatusMessage, (object) currentTask.SubTask(currentSegmentIndex).Name(), (object) Math.Abs(currentSegmentGain), (object) Math.Abs(globalGain));
            else
              this.StatusMessage = "";
          }
          else
            this.StatusMessage = "";
        }
      }
      else
      {
        if (this.m_currentPlanType != CUiAPPMainWindow.PlanType.PLAN && this.m_currentPlanType != CUiAPPMainWindow.PlanType.PLAN_AND_OPTIMIZATION || !(this.m_planManager.PlanCommand is CApAPPPostProcessingCommand planCommand))
          return;
        int currentSegmentIndex = 0;
        planCommand.GetCurrentSegmentIndex(ref currentSegmentIndex);
        CApAPPTask currentTask = planCommand.CurrentTask;
        if (currentTask == null || currentSegmentIndex < 0 || currentSegmentIndex >= currentTask.CountSubTasks())
          return;
        this.StatusMessage = string.Format(CApAPPMainWindowStringTable.PostProcessingStatusMessage, (object) currentTask.SubTask(currentSegmentIndex).Name());
      }
    }
  }

  private void HideSpecificRoboticControls()
  {
    ObservableCollection<DataGridColumn> columns = this.fgLocationGrid.Columns;
    columns[2].Visibility = Visibility.Hidden;
    columns[3].Visibility = Visibility.Hidden;
    this.cbCheckCableTwisting.Visibility = Visibility.Collapsed;
    this.spMaxJ4J6.Visibility = Visibility.Collapsed;
  }

  private void SetActiveSection()
  {
    bool i_activeSection1 = this.cbConsiderActiveSection.IsChecked.Value;
    bool i_activeSection2 = this.cbIncludeDevice.IsChecked.Value;
    if (i_activeSection1 & i_activeSection2 || !i_activeSection1 && !i_activeSection2)
    {
      this.m_taskManager.UpdateActiveSectionAndIncludeDevice(i_activeSection1);
    }
    else
    {
      this.m_taskManager.UpdateActiveSection(i_activeSection1);
      this.m_taskManager.UpdateActiveSectionForDevice(i_activeSection2);
    }
    this.m_locationsGrid.Refresh(CApAPPWaypointProperty.Clash);
  }

  private void UpdateCableTwistingChecking()
  {
    this.m_taskManager.UpdateCheckCableTwisting(this.cbCheckCableTwisting.IsChecked.Value, Convert.ToDouble(this.tbMaxJ4J6Value.Text) * TxApplication.Options.Units.AngularMultiplier);
    this.m_locationsGrid.Refresh(CApAPPWaypointProperty.Clash);
  }

  private bool RetrieveWaypointFromIndexRow(int i_index, ref int o_indexTask, ref int o_indexWp)
  {
    bool flag = false;
    int num1 = 1;
    int num2 = 0;
    foreach (CApAPPTask task in this.m_taskManager.Tasks)
    {
      if (i_index > num1 && i_index <= num1 + task.CountWaypoints())
      {
        o_indexTask = num2;
        o_indexWp = i_index - num1 - 1;
        flag = true;
        break;
      }
      num1 += task.CountWaypoints() + 1;
      ++num2;
    }
    return flag;
  }

  private void DisplayActiveSection()
  {
    this.cbConsiderActiveSection.IsEnabled = false;
    if (this.m_activeSections.Count == 0)
      this.lblActiveSectionName.Text = StringTable.AUTO_PATH_PLAN_NO_SECTION_VOLUME;
    else if (this.m_activeSections.Count > 1)
    {
      this.lblActiveSectionName.Text = StringTable.AUTO_PATH_PLAN_MULTIPLE_SECTION_VOLUMES;
    }
    else
    {
      if (this.m_activeSections.Count != 1)
        return;
      this.lblActiveSectionName.Text = ((ITxObject) this.m_activeSections[0]).Name;
      if (this.m_pathPlanningParams.OptimizationOption == 2 || this.m_pathPlanningParams.OptimizationOption == 3)
        return;
      this.cbConsiderActiveSection.IsEnabled = true;
      this.lblActiveSectionName.IsEnabled = true;
    }
  }

  private List<ITxSectionVolume> GetActiveSections()
  {
    List<ITxSectionVolume> activeSections = new List<ITxSectionVolume>();
    foreach (ITxSectionVolume allDescendant in (Collection<ITxObject>) TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxSectionVolume))))
    {
      if (((ITxSection) allDescendant).Active)
        activeSections.Add(allDescendant);
    }
    return activeSections;
  }

  private bool IsActiveSectionEnabled() => this.m_activeSections.Count == 1;

  private double GetHalfBoundingBoxDiagonalSize()
  {
    TxBoundingBox txBoundingBox = new TxBoundingBox();
    TxBoundingBoxCalculator boundingBoxCalculator = new TxBoundingBoxCalculator();
    TxObjectList txObjectList = new TxObjectList();
    foreach (TxCollisionPair pair in (Collection<ITxObject>) TxApplication.ActiveDocument.CollisionRoot.PairList)
    {
      if (pair.Active)
      {
        foreach (ITxObject first in (Collection<ITxObject>) pair.FirstList)
        {
          if (!((Collection<ITxObject>) txObjectList).Contains(first))
            ((Collection<ITxObject>) txObjectList).Add(first);
        }
        foreach (ITxObject second in (Collection<ITxObject>) pair.SecondList)
        {
          if (!((Collection<ITxObject>) txObjectList).Contains(second))
            ((Collection<ITxObject>) txObjectList).Add(second);
        }
      }
    }
    boundingBoxCalculator.Objects = txObjectList;
    TxBoundingBox minimalBoundingBox = boundingBoxCalculator.CalculateVisibleMinimalBoundingBox();
    double num1 = minimalBoundingBox.Higher.X - minimalBoundingBox.Lower.X;
    double num2 = minimalBoundingBox.Higher.Y - minimalBoundingBox.Lower.Y;
    double num3 = minimalBoundingBox.Higher.Z - minimalBoundingBox.Lower.Z;
    return Math.Sqrt(num1 * num1 + num2 * num2 + num3 * num3) / 2.0;
  }

  private void RegisterObjectFlowAbsoluteLocationChangedEvent()
  {
    for (int index1 = 0; index1 < this.m_taskManager.Tasks.Count; ++index1)
    {
      TxObjectList allLocations = this.m_taskManager.Tasks[index1].GetAllLocations();
      for (int index2 = 0; index2 < ((Collection<ITxObject>) allLocations).Count; ++index2)
      {
        TxObjectFlowLocationOperation locationOperation = ((Collection<ITxObject>) allLocations)[index2] as TxObjectFlowLocationOperation;
        if (TxObjectFlowLocationOperation.op_Inequality(locationOperation, (ITxObject) null))
          locationOperation.AbsoluteLocationChanged += new TxLocatableObject_AbsoluteLocationChangedEventHandler(this.ObjectFlowAbsoluteLocationChanged);
      }
    }
  }

  private void UnregisterObjectFlowAbsoluteLocationChangedEvent()
  {
    if (!this.m_taskManager.IsObjectFlowMode)
      return;
    for (int index1 = 0; index1 < this.m_taskManager.Tasks.Count; ++index1)
    {
      TxObjectList allLocations = this.m_taskManager.Tasks[index1].GetAllLocations();
      for (int index2 = 0; index2 < ((Collection<ITxObject>) allLocations).Count; ++index2)
      {
        TxObjectFlowLocationOperation locationOperation = ((Collection<ITxObject>) allLocations)[index2] as TxObjectFlowLocationOperation;
        if (TxObjectFlowLocationOperation.op_Inequality(locationOperation, (ITxObject) null))
          locationOperation.AbsoluteLocationChanged -= new TxLocatableObject_AbsoluteLocationChangedEventHandler(this.ObjectFlowAbsoluteLocationChanged);
      }
    }
  }

  private void ObjectFlowAbsoluteLocationChanged(
    object sender,
    TxLocatableObject_AbsoluteLocationChangedEventArgs args)
  {
    int num = -1;
    CApAPPTask capAppTask = (CApAPPTask) null;
    foreach (CApAPPTask task in this.m_taskManager.Tasks)
    {
      TxObjectList allLocations = task.GetAllLocations();
      if (sender is ITxObject itxObject)
      {
        for (int i_rank = 0; i_rank < ((Collection<ITxObject>) allLocations).Count; ++i_rank)
        {
          if (task.GetLocation(i_rank) == itxObject)
          {
            num = i_rank;
            capAppTask = task;
          }
        }
      }
    }
    if (capAppTask == null || !(capAppTask is CApAPPObjectFlowTask appObjectFlowTask))
      return;
    appObjectFlowTask.UpdateLocationFromWaypoint(num, capAppTask.Waypoint(num), capAppTask.GetLocation(num));
    appObjectFlowTask.UpdateWaypointStatus(num);
    this.m_locationsGrid.RefreshAll();
    if (!this.LimitsUserControl.IsInitialized)
      return;
    this.LimitsUserControl.UpdateLimitError();
  }

  private void UpdateDialogBeforeLaunchPlanning()
  {
    this.UpdateBorderVisibility(false);
    this.btnPlan.IsEnabled = false;
    this.btnOptimize.IsEnabled = false;
    this.btnPlanAndOptimize.IsEnabled = false;
    this.btnPlan.Refresh();
    this.btnOptimize.Refresh();
    this.btnPlanAndOptimize.Refresh();
    this.ClearProgressBars();
  }

  private void UpdateDialogBeforePlanning()
  {
    this.m_planManager.PlanningDidProgress += new PlanningDidProgressEventHandler(this.m_planCommand_PlanningDidProgress);
    this.m_planManager.PlanningDidUpdate += new PlanningDidUpdateEventHandler(this.m_planCommand_PlanningDidUpdate);
    this.m_planManager.PlanningDidEnd += new PlanningDidEndEventHandler(this.m_planCommand_PlanningDidEnd);
    this.m_planManager.WaypointDidChanged += new WaypointTypeDidChangedEventHandler(this.m_planCommand_WaypointDidChanged);
    this.m_planManager.PlanningWillEnd += new PlanningWillEndEventHandler(this.m_cappPlanCommand_PlanningWillEnd);
    if (this.m_taskManager.IsObjectFlowMode)
      this.UnregisterObjectFlowAbsoluteLocationChangedEvent();
    this.m_locationsGrid.Refresh(CApAPPWaypointProperty.Status);
    switch (this.m_currentPlanType)
    {
      case CUiAPPMainWindow.PlanType.PLAN:
        this.btnPlan.IsEnabled = true;
        this.btnPlan.Content = (object) CApAPPMainWindowStringTable.AppStopButton;
        this.btnOptimize.IsEnabled = false;
        this.btnPlanAndOptimize.IsEnabled = false;
        break;
      case CUiAPPMainWindow.PlanType.OPTIMIZATION:
        this.btnOptimize.IsEnabled = true;
        this.btnOptimize.Content = (object) CApAPPMainWindowStringTable.AppStopButton;
        this.btnPlan.IsEnabled = false;
        this.btnPlanAndOptimize.IsEnabled = false;
        break;
      case CUiAPPMainWindow.PlanType.PLAN_AND_OPTIMIZATION:
        this.btnPlanAndOptimize.IsEnabled = true;
        this.btnPlanAndOptimize.Content = (object) CApAPPMainWindowStringTable.AppStopButton;
        this.btnOptimize.IsEnabled = false;
        this.btnPlan.IsEnabled = false;
        break;
    }
    if (this.m_taskManager.IsObjectFlowMode && !this.m_taskManager.ContainsWeldOperation)
    {
      this.magnetPointPanel.IsEnabled = true;
      this.btnMagnetPoint.IsChecked = new bool?(false);
    }
    CUiAPPMainWindow.EnableMenuItem(CUiAPPMainWindow.GetSystemMenu(new WindowInteropHelper((Window) this).Handle, false), 61536U, 1U);
    this.m_locationsGrid.Refresh(CApAPPWaypointProperty.Status);
  }

  private void UpdateDialogAfterPlanning()
  {
    double actualHeight = this.fgLocationGrid.ActualHeight;
    this.UpdateBorderVisibility(true);
    this.ClearProgressBarValues();
    this.UpdatePathPlanningStatusUI();
    this.StatusMessage = "";
    this.btnOptimize.Content = (object) CApAPPMainWindowStringTable.AppPathOptimizationButton;
    this.btnPlan.Content = (object) CApAPPMainWindowStringTable.AppPathPlanningButton;
    this.btnPlanAndOptimize.Content = (object) CApAPPMainWindowStringTable.AppPlanningAndOptimizationExecuteButton;
    this.btnOptimize.IsEnabled = true;
    this.btnPlan.IsEnabled = true;
    this.btnPlanAndOptimize.IsEnabled = true;
    this.magnetPointPanel.IsEnabled = false;
    this.cbUpdateDisplay.IsEnabled = true;
    this.m_locationsGrid.UpdateView();
    CUiAPPMainWindow.EnableMenuItem(CUiAPPMainWindow.GetSystemMenu(new WindowInteropHelper((Window) this).Handle, false), 61536U, 0U);
    TxPerformanceModeEx performanceModeEx = new TxPerformanceModeEx((TxPerformanceModeType) 4);
    TxApplicationEx.PerformanceModeManager().EndMode(performanceModeEx);
    if (this.m_oldRealHeight != 0.0)
    {
      this.m_oldRealHeight += this.fgLocationGrid.ActualHeight - actualHeight;
      if (this.m_oldRealHeight < SystemParameters.WorkArea.Height)
      {
        ((FrameworkElement) this).MinHeight = this.m_oldRealHeight;
        ((FrameworkElement) this).MaxHeight = this.m_oldRealHeight;
      }
    }
    else
    {
      // ISSUE: explicit non-virtual call
      double num = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
      Rect workArea = SystemParameters.WorkArea;
      double height = workArea.Height;
      if (num > height)
      {
        // ISSUE: explicit non-virtual call
        this.m_oldRealHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
        workArea = SystemParameters.WorkArea;
        ((FrameworkElement) this).MinHeight = workArea.Height;
        workArea = SystemParameters.WorkArea;
        ((FrameworkElement) this).MaxHeight = workArea.Height;
      }
      else
      {
        // ISSUE: explicit non-virtual call
        ((FrameworkElement) this).MinHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
        // ISSUE: explicit non-virtual call
        ((FrameworkElement) this).MaxHeight = __nonvirtual (((FrameworkElement) this).Height) + (this.fgLocationGrid.ActualHeight - actualHeight);
      }
    }
    if (!this.m_taskManager.IsObjectFlowMode)
      return;
    this.RegisterObjectFlowAbsoluteLocationChangedEvent();
  }

  public void ClearProgressBars()
  {
    this.ClearProgressBarValues();
    this.ClearTimeValues();
  }

  public void ClearProgressBarValues()
  {
    this.pgbPlanningProgressBar.Value = 0.0;
    this.pgbPlanningAndOptimizationProgressBar.Value = 0.0;
    this.pgbOptimizationProgressBar.Value = 0.0;
  }

  public void ClearTimeValues()
  {
    string str = "0:00:00";
    this.tbOptimizationTime.Text = str;
    this.tbPlanTime.Text = str;
    this.tbPlanAndOptimizationTime.Text = str;
  }

  private void UpdateAllPlanningButtonVisibility(bool i_isEnabled)
  {
    this.UpdateBorderVisibility(i_isEnabled);
    this.btnPlan.IsEnabled = i_isEnabled;
    this.btnOptimize.IsEnabled = i_isEnabled;
    this.btnPlanAndOptimize.IsEnabled = i_isEnabled;
  }

  private void UpdateBorderVisibility(bool i_isEnabled)
  {
    this.gridOptimization.IsEnabled = i_isEnabled;
    this.spPlanAndOptimization.IsEnabled = i_isEnabled;
    this.spPlan.IsEnabled = i_isEnabled;
    this.gridApproachDepartAndPreProcess.IsEnabled = i_isEnabled;
    this.btnClose.IsEnabled = i_isEnabled;
    this.btnReset.IsEnabled = i_isEnabled;
    this.LimitsUserControl.IsEnabled = i_isEnabled;
    this.m_generalSettingsControl.IsEnabled = i_isEnabled;
  }

  private void DeactivateSimulationRefreshMode()
  {
    this.m_isModeWithoutRefreshEnabled = TxApplicationEx.IsInEnabledMode(new List<TxApplicationModeEx>()
    {
      new TxApplicationModeEx("SIMULATION_WITHOUT_REFRESH_MODE", false)
    });
    if (!this.m_isModeWithoutRefreshEnabled)
      return;
    TxApplicationEx.EnterMode(new TxApplicationModeEx("SIMULATION_WITHOUT_REFRESH_MODE", true));
  }

  private void ReactivateSimulationRefreshMode()
  {
    if (!this.m_isModeWithoutRefreshEnabled)
      return;
    TxApplicationEx.ExitMode(new TxApplicationModeEx("SIMULATION_WITHOUT_REFRESH_MODE", true));
  }

  private void OptimizationChanged()
  {
    bool flag = this.m_pathPlanningParams.OptimizationOption == 2 || this.m_pathPlanningParams.OptimizationOption == 3;
    this.cbConsiderActiveSection.IsEnabled = this.IsActiveSectionEnabled();
    this.cbIncludeDevice.IsEnabled = this.cbConsiderActiveSection.IsEnabled && this.cbConsiderActiveSection.IsChecked.Value && !this.m_taskManager.IsObjectFlowMode;
    KiAppOptimizationOption optimizationOption = this.m_pathPlanningParams.OptimizationOption;
    if (optimizationOption != null)
    {
      if (optimizationOption == 2)
      {
        this.JointTravelOptimizationTypeTextBox.Visibility = Visibility.Collapsed;
        this.CycleTimeOptimizationTypeTextBox.Visibility = Visibility.Visible;
        this.JointTravelOptimizationType.Visibility = Visibility.Collapsed;
        this.CycleTimeOptimizationType.Visibility = Visibility.Visible;
        this.JointTravelAndCycleTimeRadioButtonRow.Height = GridLength.Auto;
      }
      else
      {
        this.JointTravelOptimizationTypeTextBox.Visibility = Visibility.Collapsed;
        this.CycleTimeOptimizationTypeTextBox.Visibility = Visibility.Collapsed;
        this.JointTravelOptimizationType.Visibility = Visibility.Collapsed;
        this.CycleTimeOptimizationType.Visibility = Visibility.Collapsed;
        this.JointTravelAndCycleTimeRadioButtonRow.Height = new GridLength(0.0);
        ((UIElement) this).Refresh();
      }
    }
    else
    {
      this.JointTravelOptimizationTypeTextBox.Visibility = Visibility.Visible;
      this.CycleTimeOptimizationTypeTextBox.Visibility = Visibility.Collapsed;
      this.JointTravelOptimizationType.Visibility = Visibility.Visible;
      this.CycleTimeOptimizationType.Visibility = Visibility.Collapsed;
      this.JointTravelAndCycleTimeRadioButtonRow.Height = GridLength.Auto;
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  protected void NotifyPropertyChanged(string info)
  {
    if (this.PropertyChanged == null)
      return;
    this.PropertyChanged((object) this, new PropertyChangedEventArgs(info));
  }

  private void fgLocationGrid_SizeChanged(object sender, SizeChangedEventArgs e)
  {
    if (!this.m_isGridResized && !this.m_isFlexGridGroupCollapsedChanged)
      return;
    this.UpdateWindowHeight(e.NewSize.Height - e.PreviousSize.Height);
    this.m_isFlexGridGroupCollapsedChanged = false;
    this.m_isGridResized = false;
  }

  private void DataGridCell_SizeChanged(object sender, SizeChangedEventArgs e)
  {
    this.m_isGridResized = true;
  }

  private void fgLocationGrid_GroupCollapsedChanged(object sender, RoutedEventArgs e)
  {
    this.m_isFlexGridGroupCollapsedChanged = true;
  }

  private void tbMessage_SizeChanged(object sender, SizeChangedEventArgs e)
  {
    Size size = e.NewSize;
    double height1 = size.Height;
    size = e.PreviousSize;
    double height2 = size.Height;
    this.UpdateWindowHeight(height1 - height2);
  }

  private void cbFixed_CheckedChanged(object sender, EventArgs e)
  {
    System.Windows.Controls.CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
    if (this.fgLocationGrid.SelectedItems.Count > 1)
    {
      bool? isChecked = checkBox.IsChecked;
      if (isChecked.HasValue)
      {
        IList selectedItems = this.fgLocationGrid.SelectedItems;
        for (int index = 0; index < selectedItems.Count; ++index)
        {
          CApAPPWaypoint capAppWaypoint = selectedItems[index] as CApAPPWaypoint;
          isChecked = checkBox.IsChecked;
          // ISSUE: variable of a boxed type
          __Boxed<bool> local = (ValueType) isChecked.Value;
          capAppWaypoint.UILockedStatus = (object) local;
        }
      }
    }
    if (this.m_isWindowLoading || !this.LimitsUserControl.IsInitialized)
      return;
    this.LimitsUserControl.UpdateLimitError();
  }

  private void ZoneAssigmentCycleTimeRadioButton_Checked(object sender, RoutedEventArgs e)
  {
    this.m_pathPlanningParams.CTOMode = (KiAppCTOMode) 0;
  }

  private void FullCycleTimeRadioButton_Checked(object sender, RoutedEventArgs e)
  {
    this.m_pathPlanningParams.CTOMode = (KiAppCTOMode) 2;
  }

  private void QuickJointTravelRadioButton_Checked(object sender, RoutedEventArgs e)
  {
    this.m_pathPlanningParams.JointTravelOptimization = (KiAppJointTravelOptimization) 0;
  }

  private void PreciseJointTravelRadioButton_Checked(object sender, RoutedEventArgs e)
  {
    this.m_pathPlanningParams.JointTravelOptimization = (KiAppJointTravelOptimization) 1;
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  public void InitializeComponent()
  {
    if (this._contentLoaded)
      return;
    this._contentLoaded = true;
    System.Windows.Application.LoadComponent((object) this, new Uri("/DnProcessSimulateCommands;component/automaticpathplanner/cuiappmainwindow.xaml", UriKind.Relative));
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IComponentConnector.Connect(int connectionId, object target)
  {
    switch (connectionId)
    {
      case 1:
        this.dMainDialog = (CUiAPPMainWindow) target;
        ((Window) this.dMainDialog).Activated += new EventHandler(this.App_Activated);
        ((FrameworkElement) this.dMainDialog).SizeChanged += new SizeChangedEventHandler(this.dMainDialog_SizeChanged);
        ((FrameworkElement) this.dMainDialog).Loaded += new RoutedEventHandler(this.TxWindow_Loaded);
        ((Window) this.dMainDialog).Closing += new CancelEventHandler(this.TxWindow_Closed);
        break;
      case 2:
        this.fgLocationGrid = (System.Windows.Controls.DataGrid) target;
        this.fgLocationGrid.ContextMenuOpening += new ContextMenuEventHandler(this.ctmOpening);
        this.fgLocationGrid.SelectionChanged += new SelectionChangedEventHandler(this.fg_SelectionChanged);
        this.fgLocationGrid.SizeChanged += new SizeChangedEventHandler(this.fgLocationGrid_SizeChanged);
        break;
      case 4:
        this.m_fgLocationGrid_pathAndLocationColumn = (DataGridTemplateColumn) target;
        break;
      case 5:
        this.m_fgLocationGrid_fixedColumn = (DataGridTemplateColumn) target;
        break;
      case 7:
        this.m_fgLocationGrid_motionColumn = (DataGridTemplateColumn) target;
        break;
      case 8:
        this.m_fgLocationGrid_zoneColumn = (DataGridTemplateColumn) target;
        break;
      case 9:
        this.m_fgLocationGrid_clashColumn = (DataGridTemplateColumn) target;
        break;
      case 10:
        this.m_fgLocationGrid_statusColumn = (DataGridTemplateColumn) target;
        break;
      case 11:
        this.fgContextMenu = (System.Windows.Controls.ContextMenu) target;
        break;
      case 13:
        this.exPlan = (Expander) target;
        this.exPlan.SizeChanged += new SizeChangedEventHandler(this.Expander_SizeChanged);
        break;
      case 14:
        this.pgbPlanningProgressBar = (System.Windows.Controls.ProgressBar) target;
        break;
      case 15:
        this.tbPlanTime = (TextBlock) target;
        break;
      case 16 /*0x10*/:
        this.btnPlan = (System.Windows.Controls.Button) target;
        this.btnPlan.Click += new RoutedEventHandler(this.btnPlan_Click);
        this.btnPlan.SizeChanged += new SizeChangedEventHandler(this.UpdatePlanOptDoBothButtonsWidth);
        break;
      case 17:
        this.spPlan = (StackPanel) target;
        break;
      case 18:
        this.cbQuality = (System.Windows.Controls.ComboBox) target;
        this.cbQuality.DropDownClosed += new EventHandler(this.cbQuality_DropdownClosed);
        break;
      case 19:
        this.cbActivatedExtraction = (System.Windows.Controls.CheckBox) target;
        this.cbActivatedExtraction.Click += new RoutedEventHandler(this.cbActivatedExtraction_Click);
        break;
      case 20:
        this.cbConsiderActiveSection = (System.Windows.Controls.CheckBox) target;
        this.cbConsiderActiveSection.Click += new RoutedEventHandler(this.cbConsiderActiveSection_Click);
        break;
      case 21:
        this.lblActiveSectionName = (TextBlock) target;
        break;
      case 22:
        this.cbIncludeDevice = (System.Windows.Controls.CheckBox) target;
        this.cbIncludeDevice.Click += new RoutedEventHandler(this.cbIncludeDevice_Click);
        break;
      case 23:
        this.cbCheckCableTwisting = (System.Windows.Controls.CheckBox) target;
        this.cbCheckCableTwisting.Click += new RoutedEventHandler(this.cbCheckCableTwisting_Click);
        break;
      case 24:
        this.spMaxJ4J6 = (StackPanel) target;
        break;
      case 25:
        this.tbMaxJ4J6Title = (TextBlock) target;
        break;
      case 26:
        this.tbMaxJ4J6Value = (System.Windows.Controls.TextBox) target;
        this.tbMaxJ4J6Value.TextChanged += new TextChangedEventHandler(this.tbMaxJ4J6Value_TextChanged);
        this.tbMaxJ4J6Value.PreviewTextInput += new TextCompositionEventHandler(this.tbMaxJ4J6Value_PreviewTextInput);
        this.tbMaxJ4J6Value.IsKeyboardFocusedChanged += new DependencyPropertyChangedEventHandler(this.tbMaxJ4J6Value_FocusChanged);
        break;
      case 27:
        this.tbMaxJ4J6Unit = (TextBlock) target;
        break;
      case 28:
        this.gridApproachDepartAndPreProcess = (Grid) target;
        break;
      case 29:
        this.preProcessingActivation = (RowDefinition) target;
        break;
      case 30:
        this.ApproachDepartCreationParameters = (RowDefinition) target;
        break;
      case 31 /*0x1F*/:
        this.PreProcessingPanel = (StackPanel) target;
        break;
      case 32 /*0x20*/:
        this.cbActivatePreProcessing = (System.Windows.Controls.CheckBox) target;
        break;
      case 33:
        this.ApproachDepartMakerPanel = (StackPanel) target;
        break;
      case 34:
        this.cbApproachDepartCreation = (System.Windows.Controls.CheckBox) target;
        break;
      case 35:
        this.openingGunRow = (RowDefinition) target;
        break;
      case 36:
        this.perpendicularAdj = (RowDefinition) target;
        break;
      case 37:
        this.cbOpeningGun = (TextBlock) target;
        break;
      case 38:
        this.TxNumericEditBoxOpeningGunValue = (TxNumericEditBoxControl) target;
        break;
      case 39:
        this.tbOpeningLinearUnitLabel = (TextBlock) target;
        break;
      case 40:
        this.cbPerpendicularAdjustment = (TextBlock) target;
        break;
      case 41:
        this.TxNumericEditBoxOptimizationPerpendicularAdujustment = (TxNumericEditBoxControl) target;
        break;
      case 42:
        this.tbPerpendicularLinearUnitLabel = (TextBlock) target;
        break;
      case 43:
        this.ObjectFlowPathPlanningPanel = (StackPanel) target;
        break;
      case 44:
        this.cbUpdateDisplay = (System.Windows.Controls.CheckBox) target;
        break;
      case 45:
        this.magnetPointPanel = (StackPanel) target;
        break;
      case 46:
        this.btnMagnetPoint = (ToggleButton) target;
        this.btnMagnetPoint.Click += new RoutedEventHandler(this.btnMagnetPoint_Click);
        break;
      case 47:
        this.btnResetMagnetPoint = (System.Windows.Controls.Button) target;
        this.btnResetMagnetPoint.Click += new RoutedEventHandler(this.btnResetMagnetPoint_Click);
        break;
      case 48 /*0x30*/:
        this.LimitsUserControl = (CApAPPLimitsUserControl) target;
        break;
      case 49:
        this.exOptimization = (Expander) target;
        this.exOptimization.SizeChanged += new SizeChangedEventHandler(this.Expander_SizeChanged);
        break;
      case 50:
        this.pgbOptimizationProgressBar = (System.Windows.Controls.ProgressBar) target;
        break;
      case 51:
        this.tbOptimizationTime = (TextBlock) target;
        break;
      case 52:
        this.btnOptimize = (System.Windows.Controls.Button) target;
        this.btnOptimize.Click += new RoutedEventHandler(this.btnOptimize_Click);
        this.btnOptimize.SizeChanged += new SizeChangedEventHandler(this.UpdatePlanOptDoBothButtonsWidth);
        break;
      case 53:
        this.gridOptimizationType = (Grid) target;
        break;
      case 54:
        this.JointTravelAndCycleTimeRadioButtonRow = (RowDefinition) target;
        break;
      case 55:
        this.cbOptimizationType = (System.Windows.Controls.ComboBox) target;
        this.cbOptimizationType.DropDownClosed += new EventHandler(this.cbOptimization_DropdownClosed);
        break;
      case 56:
        this.JointTravelOptimizationTypeTextBox = (TextBlock) target;
        break;
      case 57:
        this.CycleTimeOptimizationTypeTextBox = (TextBlock) target;
        break;
      case 58:
        this.JointTravelOptimizationType = (StackPanel) target;
        break;
      case 59:
        this.QuickJointTravelRadioButton = (System.Windows.Controls.RadioButton) target;
        this.QuickJointTravelRadioButton.Checked += new RoutedEventHandler(this.QuickJointTravelRadioButton_Checked);
        break;
      case 60:
        this.PreciseJointTravelRadioButton = (System.Windows.Controls.RadioButton) target;
        this.PreciseJointTravelRadioButton.Checked += new RoutedEventHandler(this.PreciseJointTravelRadioButton_Checked);
        break;
      case 61:
        this.CycleTimeOptimizationType = (StackPanel) target;
        break;
      case 62:
        this.ZoneAssigmentCycleTimeRadioButton = (System.Windows.Controls.RadioButton) target;
        this.ZoneAssigmentCycleTimeRadioButton.Checked += new RoutedEventHandler(this.ZoneAssigmentCycleTimeRadioButton_Checked);
        break;
      case 63 /*0x3F*/:
        this.FullCycleTimeRadioButton = (System.Windows.Controls.RadioButton) target;
        this.FullCycleTimeRadioButton.Checked += new RoutedEventHandler(this.FullCycleTimeRadioButton_Checked);
        break;
      case 64 /*0x40*/:
        this.gridOptimization = (Grid) target;
        break;
      case 65:
        this.gridNewFullCycleTime = (Grid) target;
        break;
      case 66:
        this.m_ctoEnableTargetCycleTime = (System.Windows.Controls.CheckBox) target;
        this.m_ctoEnableTargetCycleTime.Click += new RoutedEventHandler(this.m_ctoEnableTargetCycleTime_Click);
        break;
      case 67:
        this.TxNumericEditBoxOptimizationCycleTimeTarget = (TxNumericEditBoxControl) target;
        break;
      case 68:
        this.m_ctoOptimizationTargetCycleTimeUnitLabelNewFull = (TextBlock) target;
        break;
      case 69:
        this.m_ctoEnableTimeLimitLabelNewFull = (System.Windows.Controls.CheckBox) target;
        this.m_ctoEnableTimeLimitLabelNewFull.Click += new RoutedEventHandler(this.m_ctoEnableTimeLimitLabelNewFull_Click);
        break;
      case 70:
        this.TxNumericEditBoxOptimizationTimeLimitNewFull = (TxNumericEditBoxControl) target;
        break;
      case 71:
        this.m_ctoOptimizationTimeOutUnitLabelNewFull = (TextBlock) target;
        break;
      case 72:
        this.gdClearanceOpt = (Grid) target;
        break;
      case 73:
        this.tbClearanceOptStepSize = (TxNumericEditBoxControl) target;
        break;
      case 74:
        this.tbClearanceOptUnit = (TextBlock) target;
        break;
      case 75:
        this.fgDesiredClearances = (System.Windows.Controls.DataGrid) target;
        break;
      case 76:
        this.TxNumericEditBoxEnergyMaxCycleTimeIncrease = (TxNumericEditBoxControl) target;
        break;
      case 77:
        this.TxNumericEditBoxEnergyMaxJointSpeed = (TxNumericEditBoxControl) target;
        break;
      case 78:
        this.TxNumericEditBoxEnergyMaxLinearSpeed = (TxNumericEditBoxControl) target;
        break;
      case 79:
        this.m_energyEnableTimeLimitCheckBox = (System.Windows.Controls.CheckBox) target;
        break;
      case 80 /*0x50*/:
        this.TxNumericEditBoxEnergyTimeLimit = (TxNumericEditBoxControl) target;
        break;
      case 81:
        this.m_energyOptimizationTimeOutUnitLabel = (TextBlock) target;
        break;
      case 82:
        this.exPlanAndOptimization = (Expander) target;
        this.exPlanAndOptimization.SizeChanged += new SizeChangedEventHandler(this.Expander_SizeChanged);
        break;
      case 83:
        this.tbPlanAndOptimizationTime = (TextBlock) target;
        break;
      case 84:
        this.pgbPlanningAndOptimizationProgressBar = (System.Windows.Controls.ProgressBar) target;
        break;
      case 85:
        this.btnPlanAndOptimize = (System.Windows.Controls.Button) target;
        this.btnPlanAndOptimize.Click += new RoutedEventHandler(this.btnPlanAndOpt_Click);
        this.btnPlanAndOptimize.SizeChanged += new SizeChangedEventHandler(this.UpdatePlanOptDoBothButtonsWidth);
        break;
      case 86:
        this.spPlanAndOptimization = (StackPanel) target;
        break;
      case 87:
        this.exGeneralOption = (Expander) target;
        this.exGeneralOption.SizeChanged += new SizeChangedEventHandler(this.Expander_SizeChanged);
        break;
      case 88:
        this.m_generalSettingsControl = (CUiAPPGeneralSettings) target;
        break;
      case 89:
        this.btnReset = (System.Windows.Controls.Button) target;
        this.btnReset.Click += new RoutedEventHandler(this.btnCancel_Click);
        break;
      case 90:
        this.btnClose = (System.Windows.Controls.Button) target;
        this.btnClose.Click += new RoutedEventHandler(this.btnOK_Click);
        break;
      case 91:
        this.iErrorIcon = (Image) target;
        break;
      case 92:
        this.lblPathPlanningStatus = (TextBlock) target;
        break;
      case 93:
        this.tbMessage = (TextBlock) target;
        this.tbMessage.SizeChanged += new SizeChangedEventHandler(this.tbMessage_SizeChanged);
        break;
      default:
        this._contentLoaded = true;
        break;
    }
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IStyleConnector.Connect(int connectionId, object target)
  {
    switch (connectionId)
    {
      case 3:
        ((Expander) target).Expanded += new RoutedEventHandler(this.fgLocationGrid_GroupCollapsedChanged);
        ((Expander) target).Collapsed += new RoutedEventHandler(this.fgLocationGrid_GroupCollapsedChanged);
        break;
      case 6:
        ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.cbFixed_CheckedChanged);
        break;
      case 12:
        ((Style) target).Setters.Add((SetterBase) new EventSetter()
        {
          Event = FrameworkElement.SizeChangedEvent,
          Handler = (Delegate) new SizeChangedEventHandler(this.DataGridCell_SizeChanged)
        });
        break;
    }
  }

  private enum PlanType
  {
    NONE,
    PLAN,
    OPTIMIZATION,
    PLAN_AND_OPTIMIZATION,
    APPROACH_DEPART_PLAN,
  }

  public enum PathPlanningUIStatus
  {
    NONE,
    EXTRACTING,
    PLANNING,
    OPTIMIZING,
    FINALIZING,
  }

  public enum EnergyCycleTimeZoneValidity
  {
    VALID_ZONE,
    UNKNOWN_ZONE,
    INVALID_ZONE,
  }
}
